分享一个快速设置背景的js 自动获取背景图的长宽
我来分享一个快速设置背景的js (需要jq支持!)
快速切图铺页面用---就是不需要手动输入背景图的长宽 自动获取背景图的长宽 :
<div class="wrap"> <div style="background: url(images/by_01.jpg) no-repeat top center;"></div> <div style="background: url(images/by_02.jpg) no-repeat top center;"></div> <div style="background: url(images/by_03.jpg) no-repeat top center;"></div> </div>
$(".wrap div").each(function(){ var img=$(this); var url=$(this).css('backgroundImage'); //console.log(url); s = url.match(/url\((.*?)\)/); url =s[1]; if(url[0]=="\""){url = url.slice(1,-1)} //url=url.substring(5,url.length - 2); //console.log(url); $("<img/>").attr("src", url).load(function() { realWidth = this.width; realHeight = this.height; //如果真实的宽度大于浏览器的宽度就按照100%显示 img.css("height",realHeight+"px"); }); /* var img = $(this); var realWidth;//真实的宽度 var realHeight;//真实的高度 //这里做下说明,$("<img/>")这里是创建一个临时的img标签,类似js创建一个new Image()对象! $("<img/>").attr("src", 'images/'+$(img).attr("data-image")).load(function() { realWidth = this.width; realHeight = this.height; //如果真实的宽度大于浏览器的宽度就按照100%显示 if(realWidth>=_w){ $(img).css("height",realHeight+"px"); } else{//如果小于浏览器的宽度按照原尺寸显示 $(img).css("width",realWidth+'px').css("height",realHeight+'px'); } });*/ });
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步