javascript - 为什么将鼠标悬停在图像上后 <li> 元素不会改变颜色和宽度?

标签 javascript html css

这是引起麻烦的片段:

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/

相关文章:

javascript - 在构建过程中集成js

javascript - 实现输入字段阴影时 JavaScript 出错

html - 如何使用 CSS 隐藏复选框标题

javascript - JS 脚本未按顺序下载和评估

css - 更改为@font-face 后,列表被隔开?

javascript - BootStrap 3 上的 Navbar-spy 不允许外部链接

javascript - 如何使用视频 ID 变量设置 wistia 绑定(bind)代码?

javascript - React 网站加载缓慢 - 是否由于许多静态 Assets ?

javascript - 从iframe弹出父页面中的div(多个)

html - 带有自定义标签的 CSS 宽度