简体   繁体   English

如何根据背景图像的高度和宽度设置DIV尺寸

[英]How to set DIV dimensions as per the height and width of background-image

I have a DIV with background-image. 我有带背景图像的DIV。 But my requirement is how can I extend the DIV size according to the height and width of background-image. 但是我的要求是如何根据背景图像的高度和宽度扩展DIV大小。 I have tried some code with the help of this link. 我已经通过链接尝试了一些代码。

var src = $('#divID').css('background-image').
                      replace('url', '')
                     .replace('(', '')
                     .replace(')', '')
                     .replace('"', '')
                     .replace('"', '');
$('body').append('<img id="appendedImg" src="' + src + '" style="height:0px;width:0px"');
var img = document.getElementById('appendedImg');       
var width = img.clientWidth;
var height = img.clientHeight; 
$('#appendedImg').detach();

I am just looking for any elegant solution if possible. 我只是在寻找任何可能的优雅解决方案。

You probably just need to look for width/height onload: 您可能只需要查找width / height onload:

var img = document.getElementById('appendedImg');
img.onload = function() {   
    var width = img.width;
    var height = img.height;
    console.log(width,height);
};

Also, you don't need to attach it, creating a new image should be enough. 另外,您不需要附加它,创建一个新图像就足够了。 Here's how I would do it: 这是我的处理方式:

var $div = $('#divID'),
    src = $div.css('background-image').replace(/url\(\"([^\"]+).*/,'$1');

$(new Image).load(function() {
    $div.width(this.width).height(this.height);
}).attr('src', src);

I would load the img first then get its height and width: 我先加载img,然后获取其高度和宽度:

imgSrc = 'http://ajthomas.co.uk/wp-content/themes/ajthomascouk/library/images/logo.png'

// append the temp imag
$('body').append('<img src="'+imgSrc+'" alt="" style="display:none" id="dummyImage"/>');

// get the image width and height
imgWidth = $('#dummyImage').width()+'px';
imgHeight = $('#dummyImage').height()+'px';

// remove the image
$('#dummyImage').remove();

// set the css for the div
$('#imADiv').css({height: imgHeight, width: imgWidth, 'background-image': 'url('+imgSrc+')'});

Coded it up for you here - http://jsfiddle.net/LTdtM/ 在这里为您编码-http: //jsfiddle.net/LTdtM/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM