为班级改变风格css

时间:2017-05-10 22:05:38

标签: javascript html css

这是我的代码的一部分: 想法是改变,例如类' navicon'就像你可以在函数fu()中看到的那样但它不起作用而且不能以这种或那种方式工作。改变关于id的颜色没有问题,但我不想给任何按钮一个特定的id。我的错误和误解在哪里? THX!

<!DOCTYPE html>
<html>
    <head>
          <meta charset="UTF-8">
<!        <link rel="stylesheet" href="css/navside.css" type="text/css">
          <style>
.navside {
    list-style-type: none;
        margin: 0;
        padding: 0;
    overflow: hidden;
    background-color: #333;
    }

.navside a {
    float: center;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    }

.navside a:hover {
    background-color: #ddd;
    color: black;
    }

</style>
</head>
<body>

<script>    
function fun(){
    document.getElementById("demo").style.backgroundColor="red";

    function fu(){ 
        var all = document.getElementsByClassName('navicon');
        for(var i=0;i<all.length;i++){
            all[i].style.backgroundColor='red';
        }
    }
}
</script>

<div class="navside">
    <a class="navicon" id="demo" href="#bla" onclick="fun()" >Text1</a><br>
    <a class="navicon"  href="#blubb" onclick="fu()">Text2</a>
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

问题是您将fu()的定义放在fun()内,因此无法从全局范围调用。似乎没有必要将它作为本地函数,我想这只是一个错误。全局定义它们。

function fun(){
    document.getElementById("demo").style.backgroundColor="red";
}

function fu(){ 
    var all = document.getElementsByClassName('navicon');
    for(var i=0;i<all.length;i++){
        all[i].style.backgroundColor='red';
    }
}

您应该从Javascript控制台中的错误消息中获得关于此问题的线索,说明函数fu不存在。

答案 1 :(得分:0)

您正在调用不存在的函数

这是正确的:

获取lopp内部的长度是不好的做法

function fun(){
    document.getElementById("demo").style.backgroundColor="red";
}
function fu(){ 
    var all = document.getElementsByClassName('navicon'),
        len = all.length,
        i;
    for(i=0;i<len;i+=1){
        all[i].style.backgroundColor='red';
    }
}

答案 2 :(得分:0)

function fun(){
    document.getElementById("demo").style.backgroundColor="red";
}

使用querySelectorAll可以在没有for循环的情况下实现。

function fu(){ 
    document.querySelectorAll('.navicon')
        .forEach((el) => { el.style.backgroundColor='red' });

}
相关问题