使用attr()获取背景图片网址

时间:2015-07-09 03:39:42

标签: javascript jquery

我使用attr(' style')并且能够获得低于此值的

background-image: url(http://example.com/img/123456-bg.jpg); background-size: cover;

但如何继续

123456-bg

5 个答案:

答案 0 :(得分:1)

尝试

var $div = $('#mydiv'),
  bimg = $div.css('background-image');
var match = bimg.match(/\d+-bg/),
  value = match ? match[0] : undefined;

snippet.log(value)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv" style="background-image: url(http://example.com/img/123456-bg.jpg); background-size: cover;"></div>

答案 1 :(得分:1)

或多或少像这样: http://jsfiddle.net/stdob/52ok19gr/3/

var url = $("#div").css('background-image');

var m = new URL(url.match(/url\((.*)\)/).pop());

m.filename = (m.pathname).substring( (m.pathname).lastIndexOf('/')+1 );

m.basename = m.filename.match(/(.*)\.(.*)/)[1];

console.log(m);

答案 2 :(得分:0)

改为使用

&#39;的CSS(&#34;背景图像&#34)&#39;

答案 3 :(得分:0)

试试这个......

var index = yourUrl.lastIndexOf("/") + 1;
var img = yourUrl.substr(index);
var imgName = img.substr(0, img.indexOf('.'));
alert(imgName);

答案 4 :(得分:0)

这应该有效:

var imageName = $('#yourDiv').css('background-image').match(/img\/(.*)\.jpg/)[1];