我有一个图像和一个彩色的 div 覆盖在我的图像上。 我使用 jquery 设置彩色叠加 div 宽度和高度来获取图像宽度和高度。 它工作正常。
这是我的 html:
<div class="image_overlay">
<div class="overlay"></div>
<img src="http://us.123rf.com/400wm/400/400/1xpert/1xpert1101/1xpert110100083/8712640-rainbow-cubes-3d-render-image.jpg" class="image">
</div>
<div class="image_overlay">
<div class="overlay"></div>
<img src="http://4.bp.blogspot.com/-BrLngyC1Bto/UpO-IY1kcNI/AAAAAAAALqA/1bSQRy3G_gU/s1600/Image-b%C3%A9b%C3%A9-facebook-8.jpg" class="image">
</div>
我的CSS
.image_overlay{
position:relative}
.image{
z-index:1;
width:50%;
height:auto;
}
.overlay{
background-color:rgba(13, 181, 30, 0.8);
position:absolute;
z-index:2;
}
和我的 jquery
$(".image").load(function(){
var image_h=this.height,
image_w=this.width;
$(".overlay").height(image_h);
$(".overlay").width(image_w);
});
现在我正在尝试使用 $(window).on('resize',function()...做...
这是我尝试过的:http://jsfiddle.net/o4ngj624/
谁能帮我解决这个问题?
非常感谢您的帮助,
$(document).ready(function(){
$(".image").load(function(){
var image_h=this.height,
image_w=this.width;
$(".overlay").height(image_h);
$(".overlay").width(image_w);
});
$(window).trigger('resize');
});
$(window).on('resize',function() {
var image_h=this.height,
image_w=this.width;
$(".overlay").height(image_h);
$(".overlay").width(image_w);
});
这里是 Jsfiddle,可以看到它的实际效果:
最佳答案
你应该触发 image
的 load
事件。
$(document).ready(function () {
$(".image").load(function () {
var image_h = this.height,
image_w = this.width;
//Use prev to find previous overlay
$(this).prev(".overlay").height(image_h).width(image_w);
});
});
$(window).on('resize', function () {
$(".image").trigger('load'); //Trigger load event of image
}).trigger('resize');
关于javascript - 使用 jquery 根据图像大小调整 div 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25865152/