javascript - 将鼠标悬停在列表项上时更改背景图像

标签 javascript jquery html css

如您在屏幕截图中所见,我有一个无序列表。现在这个列表的 div 有一个背景图片。我想要做的是每当我将鼠标悬停在列表项上时更改背景图像。请注意,每个元素都应将背景更改为不同的图像。我该怎么做呢?我只找到了如何更改为单个而不是多个图像的答案。

这是截图。

enter image description here

我已经将鼠标悬停在列表的第一项上。

div 的 CSS:

.body {
  display: block;
  float: left;
  background-image: url("bgdef.jpg");
  background-repeat: no-repeat;
  position: static;
  width: 100%;
  height: auto;
  margin: 0;
}

.menu {
  width: 250px;
  padding: 0;
  margin: 100px 0px 33% 75%;
  list-style-type: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
}

.menu a:link,
a:visited,
a:hover,
a:active {
  text-decoration: none;
  bottom: auto;
  padding-bottom: auto;
  text-shadow: none;
}

.menu li {
  background-color: white;
  margin: 10px;
  padding: 3px 0 3px 10%;
  border-radius: 10PX 0 0 10px;
  font-size: 20px;
}

.menu li:hover {
  background-color: green;
  margin-right: 18px;
  margin-left: 1px;
}

最佳答案

您只能通过 CSS 来做到这一点。这是一个技巧,在大多数情况下你需要使用 JS,但它的工作效果很好! (全页查看)

.wrapper {
  width:900px;
  height:600px;
  position:relative;
}

.item {
  position:relative;
  z-index:1;
}

.bg {
  position:absolute;
  top:0;
  left:0;
      width: 100%;
    height: 100%;
}

.bg img {
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  opacity:0;
  transition:all .3s ease;
}

.bg img:nth-child(1),
.item:nth-child(1):hover ~ .bg img:nth-child(1),
.item:nth-child(2):hover ~ .bg img:nth-child(2),
.item:nth-child(3):hover ~ .bg img:nth-child(3) {
  opacity:1;
}
<div class="wrapper">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="bg">
      <img src="http://i.stack.imgur.com/tq1uR.jpg" />
      <img src="http://i.stack.imgur.com/ZAy9V.jpg" />
      <img src="http://i.stack.imgur.com/xfvXS.jpg" />
    </div>
  </div>

关于javascript - 将鼠标悬停在列表项上时更改背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32420841/

相关文章:

javascript - 带定时器自动关闭弹出窗口

javascript - 使用 while 循环在 printArray 函数中获取额外的未定义值

javascript - 从外部程序定位相同的浏览器选项卡

jquery - 无法更改 jquery fullcalendar 中的标题文本颜色

html - 根据条件动态填充 div

javascript - 父组件如何在 React 中改变子组件的 props?

javascript - 对象创建期间的“this”上下文

jquery - .autocomplete 不是一个函数

javascript - 在 JS 中抓取 html 表单数据

javascript - 当到达当前卡住的 header 时,用第二个 header 替换粘性 header