首页 > 解决方案 > 如何在彼此旁边显示 2 张图像,但在悬停时只显示一张?

问题描述

我有一个巨大的图像列表,当前位于无序列表中,我现在正在尝试更改它以在悬停时在原始图像上显示另一个图像,并且在此过程中隐藏原始图像。

我几乎可以让它与下面的代码一起工作,但它只是隐藏了原始图片,而不是让新图片进入视野。

.mainImg {
  opacity: 1;
}

.mainImg:hover {
  opacity: 0;
}

.hidgeImg {
  display: none;
}

.hideImg:hover {
  display: inline-block;
}

<!-- dont know if the picture CSS is relevant but here it is -->
#pictures li {
  display: inline-block;
  width: 33%;
  margin: 0;
  text-align: center;
}

#pictures img {
  vertial-align: top;
  max-height: 350px;
}
<ul id="pictures">
  <li>
    <a href="/"><img src="image1.jpg" class="mainImg">
      <img src="image2.jpg" class="hideImg">
    </a>
  </li>
</ul>

标签: htmlcss

解决方案


我已经评论了与您相关的代码。

你非常接近,需要发生的是你需要一个父元素,当悬停时,它将处理其每个父图像的悬停事件。例如,如果您删除了mainImg在悬停时查看的功能,则没有悬停的元素可以hideImg显示。如果您有一个要悬停的父对象,它始终是“显示的”(但除了其子 img 之外从来没有任何视觉对象),那么您可以通过 thisparent 处理悬停事件。

这是通过指定悬停的内容,然后是要更改的元素的查询/选择器(EG .parent:hover .child{CSS HERE;} ​​)来实现的

<head>
  <style>
  //When parent is hovered voer, make main hidden and hideen displayed
  #hoverelement:hover .hideImg{
    display: inline-block;
  }
  #hoverelement:hover .mainImg{
    display: none;
  }
  //Hide Img is hidden by default
  .hideImg{
    display: none;
  }

  <!-- dont know if the picture CSS is relevant but here it is -->
  li {
    display: inline-block;
    width: 33%;
    margin: 0;
    text-align: center;
  }
  img {
    vertial-align: top;
    max-height: 350px;
  }
  #MainArea{
    background-color:tan;
    padding:5%;
  }
  </style>
</head>
<body>
  <div id="MainArea">
      <ul id="pictures">
      <li>
        <a href="/" id="hoverelement"><!--Add a parent element to handle hovering -->
          <img src="https://homepages.cae.wisc.edu/~ece533/images/arctichare.png" class="mainImg">
          <img src="https://homepages.cae.wisc.edu/~ece533/images/airplane.png" class="hideImg">
        </a>
      </li>
    </ul> 
  </div>
</body>

CSS


推荐阅读