问题
So here's what I have:
<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>
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.
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.
回答1:
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 */
}
Demo: http://jsbin.com/ayesec/3/edit
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>
回答2:
CSS Hover should work?
.overlay:hover {
background: url("/your/img.png");
}
来源:https://stackoverflow.com/questions/13926112/overlay-image-on-hover-on-dynamically-sized-div