悬停时覆盖图像,在动态大小的 div 上图像、大小、动态、div

2023-09-07 23:24:40 作者:男神驾到

这就是我所拥有的:

<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>