FullStack/11. JavaScript
JavaScript로 z-index 구하기
nakanara
2019. 12. 21. 00:57
반응형
레이어 팝업을 올리기 위해서 화면의 최대 z-index를 구하려고 했지만 style에서 정의된 것이 아닌 외부 CSS 파일에 정의된 z-index를 가지고 올 수 없었다.
(jQuery를 사용하는 환경에 너무 익숙해졌다)
document.defaultView.getComputedStyle(el, null)의
경우 활성화 스타일, 속성 값이 모두 연산된 결과를 돌려주므로, 스크립트 등으로 속성을 변경하였다고 해도 문제없이 가져온다.
const fnMaxZIndex = () => {
let els = [...document.querySelectorAll('body *')];
let maxZindex = 1;
els.forEach( (el) => {
let zIndex = document.defaultView.getComputedStyle(el,null).getPropertyValue("z-index");
if(!isNaN(zIndex)) {
maxZindex = (maxZindex < zIndex)? zIndex : maxZindex;
}
})
return Number(maxZindex);
}
jQuery의 style에서도 defaultView.getComputedStyle 사용하여 Style을 구하고 있었다.
// jquery-3.4.1
var getStyles = function( elem ) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
Ref
반응형