删除背景图像并使用javascript添加为图像

时间:2018-05-06 08:26:16

标签: javascript html css

我想删除style="background-image: url(http://theoldcontinent.mgtestsite.com/wp-content/uploads/2017/07/Schermafbeelding-2017-07-10-om-18.54.13-530x300.jpg); 来自

<article class="post-featured post-6792 post type-post status-publish has-post-thumbnail hentry category-tech format-standard mobile-video post-visible" style="background-image: url(http://theoldcontinent.mgtestsite.com/wp-content/uploads/2017/07/Schermafbeelding-2017-07-10-om-18.54.13-530x300.jpg);" data-video="http://www.youtube.com/watch?v=GnfNta6SosA">

并将其添加为

<img width="530" height="300" src="http://theoldcontinent.mgtestsite.com/wp-content/uploads/2017/07/kermiii-530x300.jpg" class="attachment-grid size-grid wp-post-image" alt="">

如何使用javascript删除样式并将其添加为图像,并将其保留在scr网址上。

1 个答案:

答案 0 :(得分:0)

var article = document.querySelector('article'); // Use whatever you want to get a reference to the <article>

var url = article.style.backgroundImage;
url = src.substring(5, src.length - 2);
article.style.backgroundImage = '';

var img = document.createElement('img');
img.src = url;
img.height = 300;
img.width = 530;
img.className = 'attachment-grid size-grid wp-post-image';

这将取url()内的任何内容(即图片的网址),并将其添加为srcimg。您只需imgparentNode.appendChild(img)添加到DOM(假设parentNode是您希望img所在的元素。)

请注意.substring()如何切断'url( ... )'字符串中的前五个和后两个字符。那是因为浏览器会将字符串作为'url(" ... ")'返回,而不是'url( ... )'。括号内的引号也需要被删除以获取内部的URL。