在下面的代码中,我已经说明了我想要实现的内容...通过向现有的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");
希望其他人能够发现这是一种有用的方法,在纯JavaScript中使用变量来编写CSS。
$('h4.icontitle').css('-webkit-text-size-adjust', textpercent+'%');
- Sergiu Paraschiv