分享一个快速设置背景的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');
                }
            });*/
});
原文地址:https://www.cnblogs.com/zjhblogs/p/5691623.html