使用js从样式标记更改src url

时间:2017-06-16 08:39:36

标签: javascript

我在样式标签中获取图像url默认情况下我要替换src ="#"使用js在样式标签中使用图片网址我不知道该怎么做

 <img src="#" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">

最终代码就像

 <img src="https://example.com/1.jpg" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">

4 个答案:

答案 0 :(得分:2)

您想要解析元素的当前样式,获取URL并更新src属性。

要删除style,请使用:

img.removeAttribute('style');

&#13;
&#13;
var img = document.querySelector('img'),
    // parse image URL and strip away url('')
    imgURL = img.style.backgroundImage.replace('url("','').replace('")','');
img.src = imgURL;

// remove style attribute afterwards.
img.removeAttribute('style');
&#13;
<img src="#" style="background:url('https://unsplash.it/400') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以按类名选择img代码,如下所示,并更改src属性:

&#13;
&#13;
var imgs = document.getElementsByClassName('demo-class')
var img = imgs[0];
img.src = img.style.backgroundImage.replace(/url\((.*)\)/,'$1');
img.style.backgroundImage = null
&#13;
 <img src="#" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;" class="demo-class">
&#13;
&#13;
&#13;

答案 2 :(得分:0)

    //using javascript
    document.getElementById('imgTagId').src = 'https://example.com/1.jpg';

    //using jquery
    $('#imgTagId').attr('src','https://example.com/1.jpg');


//using style background-image
var imageUrl = $('#imgTagId').css("background-image");
document.getElementById('imgTagId').src = imageUrl.split(/"/)[1];

答案 3 :(得分:-1)

为您的图片添加一个ID标记,然后您可以执行以下操作: 的document.getElementById( “图像标识”)。SRC = “../模板/ save.png”

有关更多信息,也有类似的问题 Programmatically change the src of an img tag