如何更改深埋在 div 中的 URL,并且仅当父>父>父 div 存在类时才更改它的 URL。
上下文:我正在尝试更改粘性标题中的 Logo 图像,该标题会在滚动时更改其背景颜色。当更改后的状态处于事件状态时,其中一个父 div 会添加一个名为“.bt-active”的类。
是这样的,正常状态代码是:
<section class="bdt-sticky">
<div data-id="208ba95" class=" element element-208ba95 logo widget widget-image" id=" logo" data-element_type="image.default">
<div class=" widget-container">
<div class=" image">
<a href="https://site.uk/" data- open-lightbox=""><img src="logo-1.png" class="attachment-full size-full" alt="" width="180" height="26"></a>
</div>
</div>
</div>
当粘性处于事件状态时的代码是:
<section class="bdt-sticky bdt-active">
<div data-id="208ba95" class=" element element-208ba95 logo widget widget-image" id=" logo" data-element_type="image.default">
<div class=" widget-container">
<div class=" image">
<a href="https://site.uk/" data- open-lightbox=""><img src="logo-1.png" class="attachment-full size-full" alt="" width="180" height="26"></a>
</div>
</div>
</div>
我想将处于事件状态的 Logo 更改为 src="logo-2.png"
最佳答案
img
确实 有一个类。他们中的几个。如果它们与您可能不想定位的其他图像共享,您只需查看其祖先以通过后代和/或子组合器添加更多特异性。
将 document.querySelector
与这些选择器中的任何一个一起使用都会以 img
为目标,并增加限制:
.attachment-full
.attachment-full.size-full
.image .attachment-full
.image .attachment-full.size-full
.image > .attachment-full.size-full
.image > .attachment-full
.widget-container .attachment-full
.widget-container .attachment-full.size-full
.widget-container .image .attachment-full
.widget-container .image .attachment-full.size-full
.widget-container > .image > .attachment-full.size-full
你明白了。 :-)
如果您愿意,可以将 img
放在 .attachment-full
前面以将其限制为 img
元素。
您还可以定位 src
属性:
[src="logo-1.png"]
可以与上述任何一项结合使用(例如:img[src="logo-1.png"].attachment-full
)。
实例:
function check(selector) {
console.log(selector + " => " + document.querySelector(selector) ? "found" : "not found");
}
check(".attachment-full");
check(".attachment-full.size-full");
check(".image .attachment-full");
check(".image .attachment-full.size-full");
check(".image > .attachment-full.size-full");
check(".image > .attachment-full");
check(".widget-container .attachment-full");
check(".widget-container .attachment-full.size-full");
check(".widget-container .image .attachment-full");
check(".widget-container .image .attachment-full.size-full");
check(".widget-container > .image > .attachment-full.size-full");
<section class="bdt-sticky">
<div data-id="208ba95" class=" element element-208ba95 logo widget widget-image" id=" logo" data-element_type="image.default">
<div class=" widget-container">
<div class=" image">
<a href="https://example.com/" data- open-lightbox=""><img src="https://via.placeholder.com/150x150/0000FF/808080?text=Example" class="attachment-full size-full" alt=""></a>
</div>
</div>
</div>
</section>
关于javascript - 使用 Javascript,如何定位和更改没有 ID 或类的图像的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54940520/