这是引起麻烦的片段:
function focuss() {
var x = document.getElementsByTagName("li");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "yellow";
x[i].style.color = "red";
x[i].style.width = "340px";
x[i].style.left = "-25px";
}
}
function unfocuss() {
var x = document.getElementsByTagName("li");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
x[i].style.color = "white";
x[i].style.width = "290px";
x[i].style.left = "0px";
}
}
li {
display: block;
background-color: red;
height: 33px;
border-radius: 7px;
width: 290px;
position: relative;
left: 0px;
font-size: 21px;
text-align: center;
margin-top: 3px;
}
li:hover {
width: 340px;
left: -25px;
background-color: yellow;
color: red;
}
<ul>
<a>
<li>GALLERY</li>
</a>
<a>
<li>STATISTICS</li>
</a>
<a>
<li>PLACES TO VISIT</li>
</a>
<a>
<li>HOME</li>
</a>
</ul>
<img src="f1.jpg" id="img1" onmouseover="focuss()" onmouseout="unfocuss()">
当我将鼠标直接悬停在 <li>
上时加载页面后,这些 <li>
的样式元素变化。但是,一旦我将鼠标悬停在图像上,然后将鼠标悬停在 <li>
上再次,没有变化。我做错了什么?
最佳答案
在这种情况下,您在 unfocuss() 方法中应用的内联样式将覆盖 CSS :hover 样式。我在悬停 CSS 中使用 !important 复制了您的示例。我建议谨慎使用 !important,但它可以解决您所陈述的具体问题。
function focuss() {
var x = document.getElementsByTagName("li");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "yellow";
x[i].style.color = "red";
x[i].style.width = "340px";
x[i].style.left = "-25px";
}
}
function unfocuss() {
var x = document.getElementsByTagName("li");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
x[i].style.color = "white";
x[i].style.width = "290px";
x[i].style.left = "0px";
}
}
li {
display: block;
background-color: red;
height: 33px;
border-radius: 7px;
width: 290px;
position: relative;
left: 0px;
font-size: 21px;
text-align: center;
margin-top: 3px;
}
li:hover {
width: 340px !important;
left: -25px !important;
background-color: yellow !important;
color: red !important;
}
<ul>
<a>
<li>GALLERY</li>
</a>
<a>
<li>STATISTICS</li>
</a>
<a>
<li>PLACES TO VISIT</li>
</a>
<a>
<li>HOME</li>
</a>
</ul>
<img src="f1.jpg" id="img1" onmouseover="focuss()" onmouseout="unfocuss()">
关于javascript - 为什么将鼠标悬停在图像上后 <li> 元素不会改变颜色和宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38643712/