다음 예를 살펴보십시오.
const nested = document.querySelector("#nested")
const opacity = getComputedStyle(nested).opacity
console.log(opacity)
#parent{
width: 100px;
height: 100px;
background: red;
opacity: .2;
}
#nested {
background: green;
}
<div id="parent">
<div>
<div>
<div id="nested">nested</div>
</div>
</div>
</div>
당신이 볼 수 있듯이하기 #nested
때문에 투명 #parent
그것의가 opacity
로 설정 .2
예상된다.
질문
일부 부모 요소로 #nested
인해 투명 (= 불투명도가 1 미만) 인지 어떻게 확인할 수 있습니까? 안타깝게도 위의 예와 같이 작동하지 않습니다.getComputedStyle
(내 경우 opacity
값 을 선언하는 부모 요소는 고유하지 않기 때문에 선택기로 쉽게 액세스 할 수 없습니다. 따라서 부모 요소에 ID (또는 유사한)로 직접 액세스하지 않고 순전히 중첩 된 요소로 작업합니다.)
이 솔루션을 사용하면 불투명도 규칙이 1 미만인 가장 가까운 부모 를 찾을 수 있습니다 . 이것은 아이 의 투명성에 영향을 미칠 것이 발견 된 부모라는 것을 의미합니다 .
요소 검색 은 하위 요소 인 loop로 시작for()
하므로로드가 발생하지 않습니다.
let nested = document.querySelector("#nested")
function findOpacityElement(el) {
for (; el && el !== document; el = el.parentNode) {
if (getComputedStyle(el).opacity < 1) {
console.log(el);
console.log(getComputedStyle(el).opacity);
} else {}
}
};
findOpacityElement(nested);
#parent{
width: 100px;
height: 100px;
background: red;
opacity: .2;
}
#nested {
background: green;
}
<div id="parent">
<div>
<div>
<div id="nested">nested</div>
</div>
</div>
</div>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다