最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting a div's background image with jQuery. Is there an inbuilt method to strip out the url() portion? -

programmeradmin2浏览0评论

I am using this code to get the background image of a div.

var bgImage = $('#content').css('backgroundImage');

This is returning url%28.png%29

I know you can do element.height() to get an element's height without px appended (parseInt() also works), so I was wondering if there was a similiar method for jQuery to get the actual background image minus the url() meta data.

I suppose I could use a regular expression, something like /url\((.*)\)/, but I'd rather know first if there is an built-in way.

I am using this code to get the background image of a div.

var bgImage = $('#content').css('backgroundImage');

This is returning url%28http://example.com/images/layout/content-trans.png%29

I know you can do element.height() to get an element's height without px appended (parseInt() also works), so I was wondering if there was a similiar method for jQuery to get the actual background image minus the url() meta data.

I suppose I could use a regular expression, something like /url\((.*)\)/, but I'd rather know first if there is an built-in way.

Share Improve this question edited May 13, 2013 at 0:22 alex asked May 8, 2009 at 0:26 alexalex 490k204 gold badges889 silver badges991 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 18

url() is part of the value of background-image, so I guess you need to use regex replace.

var bgImage = $('#content').css('background-image').replace(/^url|[\(\)]/g, ''); 

Ref: http://groups.google.com/group/jquery-en/browse_thread/thread/d866997cb206b35f

how about this easy solution:

bgImage.slice(bgImage.lastIndexOf('/')+1, bgImage.length - 3)
var url = /url\(\s*(['"]?)(.*?)\1\s*\)/g.exec(str)[2];

Taken from the waitForImages jQuery plugin. I'm also the author.

Something like:

var imgUrl = 'http://example.com/images/layout/image.png';
var i = imgUrl.lastIndexOf("/"); 
var filename = imgUrl.substring(i, imgUrl.length - 1);
alert(filename); 

In pure JS terms

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论