鼠标悬停在div上时更改图像

时间:2017-01-03 15:45:09

标签: javascript html css

当鼠标悬停在图像上时我可以更改图像但是当鼠标悬停在图层/ div上时如何更改图像?

<div id="layerservicewebsite">
    <a href="website%20design.html">
        <br>
        <img src="Images/symbol%20web%20design2.jpg" onmouseover="this.src='Images/symbol%20web%20design.jpg'" onmouseout="this.src='Images/symbol%20web%20design2.jpg'" width="200" height="200"> </a>
    <h2>WEBSITE DESIGN</h2>

3 个答案:

答案 0 :(得分:0)

您可以使用以下CSS:

#layerservicewebsite:hover img {
    background-image: url('image.png');
}

以下代码段:

#layerservicewebsite:hover img {
  background-image: url('https://placeholdit.imgix.net/~text?txtsize=28&bg=0099ff&txtclr=ffffff&txt=300×300&w=300&h=300&fm=png');
}
#layerservicewebsite {
  border: 1px solid lightgray;
}
<div id="layerservicewebsite">
  <a href="website%20design.html">
    <img src="Images/symbol%20web%20design2.jpg" onmouseover="this.src='Images/symbol%20web%20design.jpg'" onmouseout="this.src='Images/symbol%20web%20design2.jpg'" width="200" height="200">
  </a>
  <h2>WEBSITE DESIGN</h2>
</div>

答案 1 :(得分:0)

我会创建2个图像并给一个类。然后为父div创建一个CSS规则,使默认图像在悬停时透明。这样做的好处是能够转换两个图像,使它们淡入和淡出。

首先,为一般图像定义一个类规则:

#layerservicewebsite > img {
position: absolute;
display: block;
opacity: 1;
transition: opacity 1s ease;
/* set your left, top, width, height etc here... */
}

然后给你想要消失的图像一些类 - 例如可以隐藏。

然后:

#layerservicewebsite:hover > img.canHide {
opacity: 0;
}

答案 2 :(得分:0)

没有javascript的解决方案:

.layer {
  padding: 50px;
  background: #eee;
}
.layer img:last-child {
  display: none;
}
.layer:hover img {
  display: none;
}
.layer:hover img:last-child {
  display: inline-block;
}
<div class="layer">
  <a href="#">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Image%20One&w=350&h=150" alt="">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Image%20Two&w=350&h=150" alt="">
  </a>
  <h2>WEBSITE DESIGN</h2>
</div>