Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
挑战JavaScript从HTML类获取图像URL_Javascript_Html_Css_Html Parsing - Fatal编程技术网

挑战JavaScript从HTML类获取图像URL

挑战JavaScript从HTML类获取图像URL,javascript,html,css,html-parsing,Javascript,Html,Css,Html Parsing,这个问题与之前的其他问题不同,这里我们有一个 类名称中的样式。这让我觉得有点复杂。 我只想提醒()网站中显示的图像的url,该图像可以通过其类名访问: <div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);"> <

这个问题与之前的其他问题不同,这里我们有一个 类名称中的样式。这让我觉得有点复杂。

我只想提醒()网站中显示的图像的url,该图像可以通过其类名访问:

    <div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>
尝试了其他不同的方法,但仍然没有运气

我的输出应该是一个警报,显示以下url: “”

非常感谢您的指导。

JavaScript(ES6),121 89字节 一个衬里,代码高尔夫风格:

alert(document.querySelector('.image-container-image').style.backgroundImage.slice(5,-2))

元素上有
.style.backgroundImage
。您可以将其与substring函数一起使用以获取url

st =document.querySelector('.image-container-image').style.backgroundImage;
url = st.substring(5, st.length -2); 
url
将变成
https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg

编辑如果您想,您可以将其更改为一行代码

警报(document.querySelector('.image container image').style.backgroundImage.substring(5,document.querySelector('.image container image').style.backgroundImage.length-2))
以下是解决方案:

//从中获取图像、样式和url
var img=document.getElementsByClassName('image-container-image')[0],
style=img.currentStyle | | window.getComputedStyle(img,false),
bi=样式.背景图像.切片(4,-1);
//对于IE,我们需要将引号删除到正确的url
bi=style.backgroundImage.slice(4,-1).replace(/“/g,”);
//向用户显示url
警报('图像URL:'+bi);

alert(document.querySelector('.image container image').style.backgroundImage.toString().replace(/(url | \(| \)(| \)|“”)/g')

您是否在堆栈溢出问题上向我们提出“挑战”?或者有人“挑战”过你吗?我想也许能帮助你。你能介绍一下达到预期效果的不同方法吗?我肯定某些正则表达式可能会解决这个问题。可能重复使用
.slice(5,-2)
。节省大量字节;)
st =document.querySelector('.image-container-image').style.backgroundImage;
url = st.substring(5, st.length -2);