悬停时覆盖图像,在动态大小的 div 上 [英] Overlay image on hover, on dynamically-sized div

查看:30
本文介绍了悬停时覆盖图像,在动态大小的 div 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

<div class="overlay">
    <p>text text</p>
</div>

<div class="overlay">
    <p>text text text text text text</p>
    <p>text text text text text text</p>
    <p>text text text text text text</p>
    <p>text text text text text text</p>
</div>

我想要做的是:每当我使用类 overlay 翻转 div 时,我想要一个半透明的 5px x 5px 图像来覆盖 div.图像必须重复以填充 div 的宽度和高度.

What I want to do is this: whenever I rollover a div with the class overlay, I want a semi-transparent 5px x 5px image to overlay the div. The image would have to repeat to fill up the width and height of the div.

最好的方法是什么?我最初的想法是,每当我使用该类滚动一个 div 时,我会动态创建一个绝对定位的 div,它与我正在滚动的 div 具有相同的确切宽度和高度,并且新的 div 具有透明的重复背景图像.

What's the best way to do this? My initial thought was whenever I rollover a div with that class, I dynamically create an absolute positioned div that has the same exact width and height of the div I'm rolling over, and that new div has the transparent repeating background image.

推荐答案

可以使用伪元素,不需要JS:

You can use pseudo elements, no need for JS:

div.overlay { 
  position: relative;
}
div.overlay:hover:after {
  content: "";
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background: url(img.png);
  opacity: .5; /* if needed */
}

演示: http://jsbin.com/ayesec/3/编辑

div.overlay {
  position: relative;
  width: 300px;
  background: yellow;
}

div.overlay:hover:after {
  content: "";
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background: url(https://placekitten.com/5/5);
  opacity: .5;
}

<div class="overlay">
  <p>text text text text text text</p>
  <p>text text text text text text</p>
  <p>text text !!HOVER!! text text</p>
  <p>text text text text text text</p>
  <p>text text text text text text</p>
</div>

这篇关于悬停时覆盖图像,在动态大小的 div 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆