html - 如何使用 CSS 在图像上滑动 div?

标签 html css transition slide

在我正在处理的网页上,我有一个包含图像的 div 和另一个 div。内部 div 最初设置为

opacity: 0;

所以它是不可见的。悬停时,内部 div 应该出现在我的图像上。我已经实现了这一点,但现在我想通过让“覆盖”div(以 0.5 的不透明度出现)在图像上逐渐向下滑动来进一步改进它。理论上我可以用 JavaScript 来做,但这次它必须是纯 CSS 解决方案。到目前为止,我的解决方案只是让覆盖 div 逐渐出现(淡入)但不会下滑,因为我从来没有单独在 CSS 中这样做过。

请参阅下图以进一步了解:

Image

HTML:

<div class="img"> <img class="squareImg" src="img1.jpg"/><div class="overlay"> tweet This <br> Buy This</div></div>
    <div class="img"> <img class="squareImg" src="img3.jpg"/></div>
    <div class="img"> </img></div>

CSS

    .overlay{
    position: absolute;
    width: 200px;
    overflow-y: hidden;
    transition-property: all;
    transition-duration: .5s;
    transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
    height: 200px;
    background-color: red;
    border: 1px solid white;
    top: 10px;
    left: 10px;
    opacity: 0;
} .overlay:hover{
    cursor:pointer;
    opacity: 0.5;
    z-index: 1;
}


.img{
position: relative;
margin-bottom: 10px;
border: 2px solid yellow;
background-color: black;
width: 200px;
height: 200px;
left: 50%;
margin-left: -110px;
padding: 10px;
}

最佳答案

由于高度转换,这里是向下滑动。

改进:

  • 代替opacity , 使用 background: rgba(255,0,0,0.5)以便叠加层的内容保持完全不透明。

  • 过渡属性已简化为 transition: all .5s

  • 外边框是用 box-shadow 创建的,黑色边框现在是用 border 属性而不是 padding 创建的。

  • .overlay高度为 0,悬停时高度为 100%。它通过 left: 0 的组合在图像中拉伸(stretch)和 right: 0

  • 没有设置图片大小,大小为<img>现在控制边框和叠加层的大小,允许不同的图像大小。

完整示例

.img {
  position: relative;
  border: 10px solid black;
  box-shadow: 0 0 0 2px yellow;
  display: inline-block;
  vertical-align: top;
  cursor: pointer;
  margin: 10px;
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  transition: all .5s;
  overflow: hidden;
  height: 0;
  background: rgba(255, 0, 0, 0);
}
.img:hover .overlay,
.overlay:hover {
  height: 100%;
  background: rgba(255, 0, 0, 0.5);
}
.img > img {
  display: block;/* Prevent inline gap under image*/
}
<div class="img">
  <img src="http://www.placehold.it/200" />
  <div class="overlay">tweet This <br>Buy This</div>
</div>

<div class="img">
  <img src="http://www.placehold.it/300" />
  <div class="overlay">tweet This <br>Buy This</div>
</div>

关于html - 如何使用 CSS 在图像上滑动 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593691/

相关文章:

html - SVG 中的换行 g 元素

html - Unicode 在 Edge 中显示异常

html - 过渡动画需要一些 CSS

Android:过渡到下一个 .java 的问题?

尽可能使用 CSS 实现 jQuery UI 平滑过渡

javascript - 如何影响 Canvas 的不同方向?

javascript - 未捕获的类型错误 : Cannot Set Property 'Render' of Undefined

javascript - 在加载 DIV 之前显示微调图像

html - 位置固定菜单不以 IE 为中心

javascript - Bootstrap 模式关闭时,Firefox 18中没有触发Transitionend事件