ConvertyjQuery最接近ES6,为bg添加CSS



目标

在vuejs项目中,获取每个图像的url并将其作为背景添加到其父文章中

问题

我应该如何重构最初用jQuery编写的代码?


JS-其他作者原创

$(".polaroid").wrap("<div class='polaroid-frame'><div class='polaroid-image'>");
$(".polaroid").each(function() {
var $this = $(this);
var imgLink = $this.attr("src");
var bg = "url("+imgLink+")";
$this.closest(".polaroid-image").css({
"background-image": bg
});
});

JS-为我的项目重构

$(".polaroid article img").each(function() {
var $this = $(this);
var imgLink = $this.attr("src");
var bg = "url("+imgLink+")";
$this.closest("article").css({
"background-image": bg
});
});

我在代码笔上的演示


背景

我正在从另一个项目中获取代码,但它是用jQuery编写的。我不想使用jQuery,相反,我只需要用ES6或纯javascript编写它。

到目前为止,我发现了一个相关的问题,即在没有jQuery的情况下寻找最接近的元素,但它太不同了,无法充分利用它

我看了mozilla的文档https://developer.mozilla.org/en-US/docs/Web/API/Element/closest,这让我认为我的代码应该翻译成

el.closest("article");

但是我该如何将其包装成传递CSS值的方式呢。我查阅了w3的文档https://www.w3schools.com/js/js_htmldom_css.asp并发现了这个例子

document.getElementById("p2").style.color = "blue";

所以我想我应该做

document.[unclear what to do here].style.background-image = /* what goes here for the variable? */;

从重构的JS中,要将其转换为纯JS,需要

(1( 在所选元素上迭代(可以使用querySelectorAll轻松完成(

(2( 获取元素的src属性

(3( 将最接近的articlebackground-image设置为该src

因此,它应该非常简单:

document.querySelectorAll('.polaroid article img').forEach((img) => {
const { src } = img;
img.closest('article').style.backgroundImage = `url(${src})`;
});

请注意,当直接设置style属性时,有时您想要使用的CSS字符串(例如background-image(在Javascript中不是有效的语法。在这种情况下,通常将用破折号分隔的单词变成camelCase。(backgroundImage(

最新更新