第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 .closest() 方法爬上 DOM 樹來查找 css 中具有

如何使用 .closest() 方法爬上 DOM 樹來查找 css 中具有

犯罪嫌疑人X 2023-06-29 22:23:10
我想找到正在使用的任何元素,overflow: hidden該元素正在應(yīng)用于子元素。我正在使用.closest()需要選擇器的函數(shù)。如何指定該選擇器以包含文件overflow: hidden中使用的任何父元素.css?前任。const parentElement = this.element?.closest();
查看完整描述

2 回答

?
慕婉清6462132

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>


查看完整回答
反對 回復(fù) 2023-06-29
?
慕無忌1623718

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>


查看完整回答
反對 回復(fù) 2023-06-29
  • 2 回答
  • 0 關(guān)注
  • 418 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號