2016-07-14 20 views
2

好日子,jQuery的CSS方法並不設置CSS3變量

我與CSS3變量時,以抵消在運行項目和許多其他的事情但是JQuery的CSS方法忽略在設定一個css變種的任何企圖。我嘗試以下

$(document).ready(function() { 
 
     $('#testdiv').css('--bgc','rgb(0,0,255)'); 
 
    });
div 
 
    { 
 
     --bgc:rgb(255,0,0); 
 
     background-color:var(--bgc); 
 
     width:50px; 
 
     height:50px; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div id="testdiv"></div>

所以理論上股利應首先由50像素紅色框加載爲50像素,並儘快頁面加載完成後改變成一個藍色的盒子,不過--bgc變量永遠不會在DIV上改變。有沒有什麼方法可以在JQuery中進行設置?

+2

什麼是'--bgc'設置變量? –

+0

@AnujKumar閱讀標題 –

+0

@AnujKumar,這是一個CSS變量,請參閱後添加的CSS類。 – Jai

回答

4

我發現了一個純JavaScript解決方案:

JS:

$(document).ready(function() { 
    document.documentElement.style.setProperty('--bgc', 'rgb(0,0,255)'); 
}); 

CSS:

:root { 
    --bgc: rgb(255,0,0); 
} 

div { 
    background-color:var(--bgc); 
    width:50px; 
    height:50px; 
} 

Codepen:http://codepen.io/theblindprophet/pen/yJpZNb

參考:Variables why should you care?

+0

謝謝,這似乎工作,我想能夠設置它在JQuery集合,但我想$()。each()將不得不做的 – KaoSDlanor

0

您可以通過JavaScript的香草

$(document).ready(function() { 
    $('#testdiv')[0].style.setProperty('--bgc', 'rgb(0, 0,255)'); 
}); 

$(document).ready(function() { 
 
    $('#testdiv')[0].style.setProperty('--bgc', 'rgb(0,0,255)'); 
 
});
div 
 
{ 
 
    --bgc:rgb(255,0,0); 
 
    background-color:var(--bgc); 
 
    width:50px; 
 
    height:50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="testdiv"></div>

+0

香草JavaScript在你的答案? – Jai

+0

'$('#testdiv')'不返回數組。你不應該在這裏需要'[0]' – theblindprophet

+0

@Jai:'.style.setProperty()' @theblindprophet在沒有'[0]' – user1636505