Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript更改外部CSS的属性_Javascript_Css_External - Fatal编程技术网

使用javascript更改外部CSS的属性

使用javascript更改外部CSS的属性,javascript,css,external,Javascript,Css,External,首先,抱歉英语不好 嗯,我需要使用javascript更改所有Parragraph的color属性,以下是我的html和JS代码: <body> <p>Parragraph one</p> <p>Parragraph two</p> <button onclick="CE()">change style</button> </body> for (var j=0;j<document.styl

首先,抱歉英语不好

嗯,我需要使用javascript更改所有Parragraph的color属性,以下是我的html和JS代码:

<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";
}
我也尝试用以下内容更改它:
document.styleSheets[0].cssRules[0].style.backgroundColor=“#FF0000”

(尝试更改背景颜色,只是为了看看它是否有效,但仅在Mozilla Firefox上有效)

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

不使用jQuery,您可以迭代所有
标记,并使用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>

函数CE()
{
var段落=document.getElementsByTagName(“p”);
对于(变量i=0;i
在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');  
            });

与其尝试使用JS来更新样式表本身,为什么不简单地使用JS向元素添加一个类,该类(显然)将具有所需的颜色?如果您对jQuery感兴趣,那么使用它非常简单,我认为他不想使用jQueryWell,那么他可以在没有jQuery的情况下手动使用和编写函数。:-)太好了!我留着这个:)
.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');  
            });