首页 > 解决方案 > 使用javascript删除背景图像并添加为图像

问题描述

我想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 url。

标签: javascripthtmlcss

解决方案


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()(即图像的 url)并将其添加为srcto img。您可以添加img到 DOM 中parentNode.appendChild(img)(假设parentNode是您想要的元素img)。

请注意.substring()将如何截断字符串中的前五个和最后两个字符'url( ... )'。那是因为浏览器会将字符串返回为'url(" ... ")',而不是'url( ... )'括号内的引号也需要剪掉才能得到里面的url。


推荐阅读