挑战JavaScript从HTML类中获取图像URL

时间:2017-07-05 19:53:18

标签: javascript html css html-parsing

此问题与之前的其他问题不同,因为我们在这里有一个问题  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

非常感谢您的指导。

4 个答案:

答案 0 :(得分:4)

JavaScript(ES6), 121 89字节

单线,代码高尔夫风格:

&#13;
&#13;
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;
&#13;
&#13;

101字节替代

即使background-image存在于外部样式表中,

getComputedStyle()仍然有效:

&#13;
&#13;
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;
&#13;
&#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

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

&#13;
&#13;
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;
&#13;
&#13;

答案 2 :(得分:0)

以下是解决方案:

&#13;
&#13;
// 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;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
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;
&#13;
&#13;

相关问题