【发布时间】:2013-08-27 15:13:34
【问题描述】:
在下面的代码中,我已经说明了我想要实现的目标...... 通过向其添加新规则来更改现有 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 中的变量的有用方法。
【问题讨论】:
-
你想用 javascript 或 jquery rite 改变 css 吗?
-
为什么不使用 jQuery 或类似的库?
$('h4.icontitle').css('-webkit-text-size-adjust', textpercent+'%'); -
请只使用Javascript。此站点中没有库(到目前为止)。
-
已解决。查看对问题的修改。
标签: javascript css class dynamic stylesheet