2 回答

TA貢獻1804條經(jīng)驗 獲得超2個贊
您不能使用closest
來選擇特定的 CSS 屬性,只有 CSS選擇器可以使用它來選擇您想要的 HTML。
您需要編寫一個函數(shù)來遍歷 DOM 并評估它傳遞的每個元素。然后,當它受到點擊時,它會停止并返回具有該設(shè)置屬性的元素。
在 的幫助下,window.getComputedStyle
您可以獲取元素上設(shè)置的樣式。請注意,這還考慮了那些不是在樣式表中專門設(shè)置而是由瀏覽器設(shè)置的樣式。
// Select grand child element.
const grandChild = document.querySelector('.grand-child');
/**
?* Traverse the DOM upwards and checks the computed styles
?* of each element is passes. Compares the value of the?
?* requested property with the passed value and returns?
?* the element if the value is a match
?*
?* @param? ?{HTMLElement} element Element to start from.
?* @param? ?{string} property CSS property to research.
?* @param? ?{string} value Value to compare CSS property value with.
?* @returns {HTMLElement|null}
?*/
const findParentWithCSS = (element, property, value) => {
? while(element !== null) {
? ? const style = window.getComputedStyle(element);
? ? const propValue = style.getPropertyValue(property);
? ? if (propValue === value) {
? ? ? return element;
? ? }
? ? element = element.parentElement;
? }
? return null;
};
const result = findParentWithCSS(grandChild, 'overflow', 'hidden');
console.log(result);
.parent {
? overflow: hidden;
}
<div class="grand-parent">
? Grand Parent
? <div class="parent">
? ? Parent, I have <code>overflow: hidden</code>
? ? <div class="child">
? ? ? Child
? ? ? <div class="grand-child">
? ? ? ? Grandchild
? ? ? </div>
? ? </div>
? </div>
</div>

TA貢獻1744條經(jīng)驗 獲得超4個贊
overflow hidden在我的示例中,JavaScript 邏輯從方法指定的父級開始查找具有指定樣式的子級closest()。
var container_box = document.querySelector('.container_box');
var closest_element = container_box.closest('.container');
for (let elem of closest_element.children) {
if (elem.matches('.container_box')) {
if (elem.getAttribute('style') == 'overflow: hidden;') {
console.log(elem);
elem.setAttribute('style', 'overflow: hidden; background-color: green;');
};
}
}
<div class="container">
<div class="container_box">1</div>
<div class="container_box" style="overflow: hidden;">2</div>
<div class="container_box">3</div>
<div class="container_box">4</div>
<div class="container_box">5</div>
</div>
添加回答
舉報