在下面的代碼中,我已經說明了我正在嘗試實現的內容... 通過向其添加新規則來更改現有的CSS類。如何將新規則添加到現有的CSS類
<head>
<style>
h4.icontitle
{font-size: 22pt;}
</style>
</head>
<body>
<script type="text/javascript">
textpercent = 84;
document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null);
</script>
<h4> hello </h4>
</body>
這是用於在不同尺寸的屏幕上運行的網站的預處理元素。 其結果將是...
h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}
檢查DOM時,這將是可見的。
任何想法將是最受歡迎的。僅限Javascript - 這裏沒有JQuery ...
已解決。
大量的試驗和錯誤之後,這裏是一個工作功能,允許JavaScript直接插入樣式到CSS
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
與
changeCSS("h4.icontitle","backgroundColor", "green");
希望別人叫會發現這是一個有用的方法在純CSS中使用CSS中的變量。
ü要使用JavaScript或jQuery的儀式改變CSS? – iJade
爲什麼不使用jQuery或類似的庫? '$('h4.icontitle').css(' - webkit-text-size-adjust',textpercent +'%');' –
Javascript only please。在這個網站沒有圖書館(到目前爲止)。 – TJS101