如何从style属性获取图片url

我有这样的html DOM我想抓住图像的url

  <img src="constant/spacer.gif" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb"> <img src="constant/spacer.gif" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb"> 

我的预期输出: ["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];

现在我正在使用这个代码

 arr = []; $('.images-thumb').each(function(){ arr.push($(this).attr('style')); // furthur i don't know }); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb"> <img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb"> 

Furthur我不知道如何抓取

 ["https://example1.com/image/image1.png","https://example1.com/image/image1.png"]; 

请提前帮助我

你可以这样做:

url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, ''); 这将从结尾删除url('url("从string的开始,如果存在的话)和")

 arr = []; $('.images-thumb').each(function(){ var $style = $(this).attr('style'); var $url = $style.replace(/^background-image:url\(["']?/, '').replace(/["']?\)$/, '').replace(/\)/, ''); arr.push($url); // further know you know :-P }); console.log(arr); 

将不需要的文本replace为空string“”:

示例代码片段:

 arr = []; $('.images-thumb').each(function() { arr.push($(this).css("background-image").replace("url(\"", "").replace("\")", "")); }); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb"> <img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb"> 

你可以简单地使用

 var images = document.querySelectorAll('.images-thumb'); var image, arr=[]; for(var i=0; i<images.length;i++){ image = window.getComputedStyle(images[i]).backgroundImage; arr.push(image.substr(5, image.length-7)); } console.log(arr); 

纯JS方法来抓取元素的所有样式。

  You can give the image path in src attribute, otherwise the script will be like below arr = []; $('.images-thumb').each(function(){ var txt = $(this).attr('style'); first = txt.indexOf('('); second = txt.indexOf(')'); arr.push(txt.substr(first+1,second-first-1)); }); console.log(arr); Just check once 

你可以使用JQuery css("background-image")select器和正则expression式来获得所需的结果。

 arr = []; $('.images-thumb').each(function(){ arr.push($(this).css("background-image").replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')); }); console.log(arr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb"> <img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">