javascript删除事件监听器?

时间:2013-09-05 16:16:13

标签: javascript html css events

在我的测试网页上,有一个类似的链接:

<a href="default.html?tab=1" id="t1" onclick="switchf('home',this)">HOME</a>

它的风格是这样的:

nav > a {
    text-decoration: none;
    color: #0000aa;
    display: inline-block;
        width: 80px;
    padding: 0 10px;
}
nav > a:hover {
    background-color: #eeeeee;
}

switchf()(切换字段)是这样的:

function switchf(field,tab) {       
    document.getElementById("home").style.display = "none";
    document.getElementById("about").style.display = "none";
    document.getElementById("account").style.display = "none";
    document.getElementById("contact").style.display = "none";

    document.getElementById("t1").style.backgroundColor = "#dddddd";
    document.getElementById("t2").style.backgroundColor = "#dddddd";
    document.getElementById("t3").style.backgroundColor = "#dddddd";
        document.getElementById("t4").style.backgroundColor = "#dddddd";

    document.getElementById(field).style.display = "inline-block";
    tab.style.backgroundColor = "#cccccc";
}

链接基本上充当选项卡,以显示不同的内容。还有其他三个人喜欢它。

JavaScript可以正常切换标签,但是当我使用switchf()后将鼠标悬停在标签上时,它不会再改变颜色了。

我的代码有问题吗?

感谢。

修改

这就是我修复我的方式:

首先,我在所有链接中添加了class="tab",所以它们看起来像这样:

<a href="?tab=1" id="t1" class="tab" onclick="switchf('home',this)">HOME</a><br />

第二,我更改了javascript,以便函数switchf()是这样的:

function switchf(field,tab) {       
    document.getElementById("home").style.display = "none";
    document.getElementById("about").style.display = "none";
    document.getElementById("account").style.display = "none";
    document.getElementById("contact").style.display = "none";

    var t = document.getElementsByClassName("tag");  // here is different
    for(var i = 0; i < t.length; i++) {
        t[i].style.backgroundColor = "#dddddd";
        t[i].addEventListener("mouseover");
        t[i].addEventListener("mouseout");
    }

    document.getElementById(field).style.display = "inline-block";
    tab.style.backgroundColor = "#cccccc";
}

并且有效。

1 个答案:

答案 0 :(得分:8)

内联CSS优先于样式表。点击链接后,它会为所有链接设置background-color属性,因此当您将鼠标悬停在链接上时,所有链接都不会改变颜色。

除了对元素中的样式进行硬编码之外,您可以尝试在链接中添加CSS类(如page-active)并根据需要设置这些元素的样式。

另一个可以帮助您清除旧类的替代方法是在页面中添加一个类或ID,并根据需要使用它来隐藏/显示链接。

<style>
nav > a {
    display: none;
}
#page-about nav > a#link-home {
    display: inline-block;
}
<body id="page-about">
    <nav>
        <a href="?tab=home" id="link-home">Home</a>
        <a href="?tab=about" id="link-about">About</a>
    </nav>
</body>

这应该给你一个大致的想法,抛光它是读者的练习。