此问题与之前的其他问题不同,因为我们在这里有一个问题 STALLE在CLASS名称中。这让我觉得有点复杂。
我想提醒()只有网站上显示的图片的网址,可以通过其类名访问:
<div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>
我试着这样做:
alert( (document.querySelector('.image-container-image').textContent) );
尝试了其他不同的方式,但仍然没有运气。
我的输出应该是一个警告,显示以下网址: “https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg”
非常感谢您的指导。
答案 0 :(得分:4)
单线,代码高尔夫风格:
alert(document.querySelector('.image-container-image').style.backgroundImage.slice(5,-2))
&#13;
<div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);"></div>
&#13;
background-image
存在于外部样式表中, getComputedStyle()
仍然有效:
alert(getComputedStyle(document.querySelector('.image-container-image')).backgroundImage.slice(5,-2))
&#13;
.image-container-image{background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);}
&#13;
<div class='image-container-image'></div>
&#13;
答案 1 :(得分:0)
您有.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
编辑如果您愿意,可以将其更改为一行代码。
alert(document.querySelector('.image-container-image').style.backgroundImage.substring(5, document.querySelector('.image-container-image').style.backgroundImage.length -2))
&#13;
<div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);"></div>
&#13;
答案 2 :(得分:0)
以下是解决方案:
// Get the image, style and the url from it
var img = document.getElementsByClassName('image-container-image')[0],
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1);
// For IE we need to remove quotes to the proper url
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
// Display the url to the user
alert('Image URL: ' + bi);
&#13;
<div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>
&#13;
答案 3 :(得分:0)
alert(document.querySelector('.image-container-image').style.backgroundImage.toString().replace(/(url|\(|\)|")/g, ''))
&#13;
<div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>
&#13;