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

标签 javascript jquery

我有一个带有背景图像的 DIV。但我的要求是如何根据背景图像的高度和宽度扩展DIV大小。我在 this 的帮助下尝试了一些代码链接。

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);

关于javascript - 如何根据背景图像的高度和宽度设置DIV尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10830895/

相关文章:

javascript - onclick 提交上的数据库更新字段不起作用

javascript - 在升序和降序之间切换列排序

javascript - 每次我通过按钮调用ajax时如何重用jsonp url中的jsonp响应变量?

javascript - 重构生成 HTML 的 JavaScript

javascript - 如何使用 underscore.js 将同一对象克隆为三个对象

javascript - 使用 jquery draggable/droppable 通过类定位特定的 div

javascript - 如何在 jQuery UI Selectmenu 中触发 'select' 事件

javascript - 向右滑动时删除 div

javascript - 为什么上下文旋转后图像质量会下降?

javascript - 如何检查数组中是否找到输入?