我有一个带有背景图像的 DIV。但我的要求是如何根据背景图像的高度和宽度扩展DIV大小。我在以下代码的帮助下尝试了一些代码this https://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript 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();
如果可能的话,我只是在寻找任何优雅的解决方案。
您可能只需要查找加载时的宽度/高度:
var img = document.getElementById('appendedImg');
img.onload = function() {
var width = img.width;
var height = img.height;
console.log(width,height);
};
另外,您不需要附加它,创建一个新图像就足够了。我会这样做:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)