使用javascript删除背景图像并添加为图像
我想删除使用javascript删除背景图像并添加为图像,javascript,html,css,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); 从 并将其添加为 <img width="530" height="300" src="http://theoldcontinent.mgtestsite.com/wp-content/u
style=“background image:url(http://theoldcontinent.mgtestsite.com/wp-content/uploads/2017/07/Schermafbeelding-2017-07-10-om-18.54.13-530x300.jpg);
从
并将其添加为
<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 url上。var article=document.querySelector('article');//使用您想要的任何东西来获取对
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';
var url=article.style.backgroundImage;
url=src.substring(5,src.length-2);
article.style.backgroundImage='';
var img=document.createElement('img');
img.src=url;
img.高度=300;
img.width=530;
img.className='附件网格大小网格wp post图像';
这将获取url()
(即图像的url)中的任何内容,并将其作为src
添加到img
。您只需使用parentNode.appendChild(img)
(假设parentNode
是您想要img
的元素)将img
添加到DOM中即可
请注意
.substring()
将如何切掉'url(…)'
字符串中的前五个字符和最后两个字符。这是因为浏览器将返回字符串作为'url(…”)
,而不是'url(…)“
括号内的引号也需要删掉,以获取其中的url。删除类以删除样式
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';