0

First of all, sorry for bad english.

Well, I need to change the color property of all parragraphs, using javascript, here's my html&JS code:

<body>
<p>Parragraph one</p>
<p>Parragraph two</p>
<button onclick="CE()">change style</button>
</body>

for (var j=0;j<document.styleSheets[0].cssRules.length;j++) {
  if(document.styleSheets[0].cssRules[j].selectorText='p')
    document.styleSheets[0].cssRules[j].style.color="#FF0000";
}

And this is my CSS code:

p{
    color: green;
    font-size: 20px;
    font-weight: bold;
    font-family: arial;
}

I tried to change it with this too: document.styleSheets[0].cssRules[0].style.backgroundColor="#FF0000"; (trying to change the background color, just to see if it works, but only works on Mozilla Firefox)

4

3 回答 3

0

在不使用 Jquery 的情况下,您可以遍历所有<p>标签并使用 javascript 添加一个 css 类。像这样的东西应该可以工作,虽然我还没有测试过。

<script>
function CE()
{
    var paragraphs = document.getElementsByTagName("p");
    for(var i = 0; i < paragraphs.length; i++)
    {
        paragraphs[i].setAttribute("class", "theme")
    }
}
</script>
<style>
.theme{
    color: green;
    font-size: 20px;
    font-weight: bold;
    font-family: arial;
}
</style>
于 2013-11-05T10:09:18.313 回答
0

使用您想要的颜色创建另一个类,然后使用 jQuery 添加和删除您认为合适的类。

于 2013-11-05T10:01:39.623 回答
0

向您的 css 中编写一个新类并遍历所有 p 元素并添加新类:

.p-different-color{
    color: green;
    font-size: 20px;
    font-weight: bold;
    font-family: arial;
}    

$("p").each(function(index, element) {       // note that the .each() handler has two parameters that can be used also
            $(this).removeClass();              // "this" inside the .each() handler function is the current DOM element in the iteration
            $(this).addClass('p-different-color');  
            });
于 2013-11-05T10:09:36.267 回答