如何在jQuery中获取背景图片大小? [英] How do I get background image size in jQuery?

查看:356
本文介绍了如何在jQuery中获取背景图片大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单。如何在jQuery中获取div的背景图片大小(宽度和高度)。是甚么可能?我认为这将工作:

The problem is simple. How do I get a div's background image size (width and height) in jQuery. Is it even possible? I thought this would work:

jQuery('#myDiv').css('background-image').height();

我得到的错误信息是这不是一个函数。

The error message I get is that this is not a function.

推荐答案

您必须这样做:

var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
bgImg.hide();
bgImg.bind('load', function()
{
    var height = $(this).height();
    alert(height);
});
$('#myDiv').append(bgImg);
bgImg.attr('src', url);


$ b b

由于代码的简单性,您不能在背景图片的网址中使用括号或引号,但是代码可以扩展以获得更大的支持,我只是想表达一般的想法。

Due to the simplicity of the code, you cannot use parenthesis or quotation marks in the URLs of your background images. However, the code could be extended for greater support. I just wanted to convey the general idea.

这篇关于如何在jQuery中获取背景图片大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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