给具有相同类的两个元素一个唯一的id



我使用Visual Composer在Wordpress中工作,我有一个切换容器。从本质上讲,我点击每个选项卡,下面的内容就会发生变化。我想通过css为每个选项卡分配一个不同的图像作为背景。然而,我已经实现了这一点,因为每个选项卡都有相同的类名(由可视化编辑器提供(,所以图像是相同的。我需要弄清楚如何给每个选项卡赋予它自己的唯一id,这样我就可以给每个选项卡提供它自己的背景图像——但由于我不能直接编辑html,我想我需要用javascript来做这件事。有人知道我怎样才能做到这一点吗?下面是html代码:

<div class="vce-toggle-container-tab">
<a class="vce-toggle-container-tab-title">Test 1</a>
</div>
<div class="vce-toggle-container-tab">
<a class="vce-toggle-container-tab-title">Test 2</a>
</div>

和我的css添加背景图像:

a.vce-toggle-container-tab-title {
background-image: url("https://katherinemade.com/staging/wp-content/uploads/2021/03/0I1A5234-3.jpg") !important;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
width: 500px;
height: 500px;
}

我希望我能解释清楚。如果不理解,请告诉我,我会再试一次。

您可以使用第n个子或第n个类型选择器,而不需要js,如下所示

a.vce-toggle-container-tab-title {
background-position: center;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
display: block;
width: 100px;
height: 100px;
}
.vce-toggle-container-tab:nth-of-type(1) a.vce-toggle-container-tab-title {
background-image: url("https://via.placeholder.com/150?text=one") !important;
}
.vce-toggle-container-tab:nth-of-type(2) a.vce-toggle-container-tab-title {
background-image: url("https://via.placeholder.com/150/0000FF/808080?text=two") !important;
}
.vce-toggle-container-tab:nth-of-type(3) a.vce-toggle-container-tab-title {
background-image: url("https://via.placeholder.com/150?text=THREE") !important;
}
<div class="vce-toggle-container-tab">
<a class="vce-toggle-container-tab-title">Test 1</a>
</div>
<div class="vce-toggle-container-tab">
<a class="vce-toggle-container-tab-title">Test 2</a>
</div>
<div class="vce-toggle-container-tab">
<a class="vce-toggle-container-tab-title">Test 3</a>
</div>

我不熟悉Wordpress,我不确定你是否可以添加javascript,但如果可以的话,如果页面中只有这些div具有类"vce toggle container tab",下面的代码可以帮助你:

const divs = document.querySelectorAll('.vce-toggle-container-tab');
//first image
divs[0].style.backgroundImage = "url('https://katherinemade.com/staging/wp-content/uploads/2021/03/0I1A5234-3.jpg')";
//second image
divs[1].style.backgroundImage = "url('https://katherinemade.com/staging/wp-content/uploads/2021/03/0I1A5234-3.jpg')";

最新更新