jquery动态设置banner高度,确保banner高度为图片高度

$(function(){
    // 刚开始这么写的,但是h高度偶尔还是会被设置为0
// $(".banner .bd img").load(function(){ // var h = $(".banner .bd img").height(); // console.log('h:',h); // $(".banner").css("height",h); // })
//修改后,用一下方式设置banner高度,实现效果
$(".banner .bd img").on("load",function(){ var img=new Image(); img.src=this.src; // console.log('屏幕宽,图片宽,图片高:',document.body.scrollWidth ,img.width,img.height); var h = (img.height * document.body.scrollWidth) / img.width; // console.log('h3:',h); $(".banner").css("height",h); });
$(window).resize(
function() { var h = $(".banner .bd img").height(); $(".banner").css("height",h); }); })
原文地址:https://www.cnblogs.com/duanzhenzhen/p/12841195.html