javascript - 使用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。
解决方案
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)并将其添加为src
to img
。您可以添加img
到 DOM 中parentNode.appendChild(img)
(假设parentNode
是您想要的元素img
)。
请注意.substring()
将如何截断字符串中的前五个和最后两个字符'url( ... )'
。那是因为浏览器会将字符串返回为'url(" ... ")'
,而不是'url( ... )'
括号内的引号也需要剪掉才能得到里面的url。
推荐阅读
- sql - 如何比较同一个表中的多行并用不同的值标记它们?
- flutter - flutter run -v 不断显示正在启动一个新的守护进程,xx忙的守护进程无法重用,使用--status查看详情
- javascript - 为什么赛普拉斯在运行 get 命令后说我的元素已分离?
- python - 如何在 argparse 中排序
- c# - 大量数据未在 Azure 事件中心发布
- reactjs - 如何在 VS Code 调试器中命中 React 钩子断点?
- 3d - 如何在着色器文件中将在 xyz 轴上移动对象和调整大小合并为一个?
- vim - 在 Vim 中,如何对多个文件重复多次替换?
- tensorflow - 使用 tf.keras.models.load_model 重新加载后保存的模型请求不同的输入形状 -> 未跟踪的函数(embeddings_layer)
- sql - 如何获取达到最后一个意图的表的行(基于时间戳)