如何根据背景图像的高度和宽度设置DIV尺寸 [英] How to set DIV dimensions as per the height and width of background-image

查看:220
本文介绍了如何根据背景图像的高度和宽度设置DIV尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DIV with background-image. But my requirement is how can I extend the DIV size according to the height and width of background-image. 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.

推荐答案

你可能只需要寻找宽度/高度onload:

You probably just need to look for 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);

这篇关于如何根据背景图像的高度和宽度设置DIV尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆