如何编写一个函数,该函数将从 div 的内联样式中获取背景图像并删除该 div,并在其位置使用 <img>
标签?
这是我的 div 的样子:
<div class="img_is" style="background-image: url(//domain.com/images/image1.png);"></div>
我将有几个这样的 div,并且每个 div 的 img 源都不同。
现在我如何编写一个函数来获取背景图像的 src 并将它们放入 <img src>
中并隐藏div?
我想到了这段代码,但无法真正弄清楚如何反转它。请帮忙。如果您发现问题或对此有任何疑问,请告诉我。
我的代码:
var images = $('li > img');
images.each(function(){
$(this).parent().css('background-image', 'url(' + $(this).attr('src') + ')');
$(this).hide(); // to hide it
$(this).remove(); // to remove it from the markup
});
最佳答案
这是一个使用带有函数的 replaceWith
重载的选项:
$('.img_is').replaceWith(function () {
return $('<img/>', {
src: $(this).css('background-image').replace(/url\(([^\)]+)\)/g, '$1')
});
});
关于javascript - 我如何编写 JQuery 函数来从内联样式 div 中获取背景图像并将其放入图像标签中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19668985/