Jon*_*Lam 0 html javascript css events
在我的测试网页上,有一个像这样的链接:
<a href="default.html?tab=1" id="t1" onclick="switchf('home',this)">HOME</a>
Run Code Online (Sandbox Code Playgroud)
它的风格是这样的:
nav > a {
text-decoration: none;
color: #0000aa;
display: inline-block;
width: 80px;
padding: 0 10px;
}
nav > a:hover {
background-color: #eeeeee;
}
Run Code Online (Sandbox Code Playgroud)
和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";
}
Run Code Online (Sandbox Code Playgroud)
链接基本上充当选项卡,以显示不同的东西.还有其他三个人喜欢它.
JavaScript可以很好地切换选项卡,但是当我在使用后将鼠标悬停在选项卡上时switchf(),它不会再改变颜色了.
我的代码有问题吗?
谢谢.
编辑
这是我固定我的方式:
首先,我添加class="tab"了所有链接,所以它们看起来像这样:
<a href="?tab=1" id="t1" class="tab" onclick="switchf('home',this)">HOME</a><br />
Run Code Online (Sandbox Code Playgroud)
第二,我改变了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";
}
Run Code Online (Sandbox Code Playgroud)
它起作用了.
内联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>
Run Code Online (Sandbox Code Playgroud)
这应该给你一个大致的想法,抛光它是读者的练习.