문서에서 가장 높은 Z-색인을 어떻게 알아낼 수 있나요?
문제
내 문서에서 가장 높은 Z-색인으로 투명한 텍스트 이미지가 포함된 div를 설정하기 위해 숫자 10,000을 선택했고 문제가 해결되었습니다.
이전에는 숫자 3으로 추측했지만 아무런 효과가 없었습니다.
그렇다면 z-index가 다른 모든 요소보다 더 높은지 알아내는 보다 과학적인 방법이 있습니까?
Firebug에서 이 측정항목을 찾으려고 했지만 찾을 수 없습니다.
해결책
당신은 전화 할 수 있습니다 findHighestZIndex
다음과 같은 'div'와 같은 특정 요소 유형의 경우 :
findHighestZIndex('div');
a findHighestZindex
다음과 같이 정의 된 함수 :
function findHighestZIndex(elem)
{
var elems = document.getElementsByTagName(elem);
var highest = 0;
for (var i = 0; i < elems.length; i++)
{
var zindex=document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("z-index");
if ((zindex > highest) && (zindex != 'auto'))
{
highest = zindex;
}
}
return highest;
}
다른 팁
명확성을 위해 Abcoder 사이트에서 일부 코드를 훔치기 :
var maxZ = Math.max.apply(null,
$.map($('body *'), function(e,n) {
if ($(e).css('position') != 'static')
return parseInt($(e).css('z-index')) || 1;
}));
더 깨끗한 접근 방식을 사용합니다
function maxZIndex() {
return Array.from(document.querySelectorAll('body *'))
.map(a => parseFloat(window.getComputedStyle(a).zIndex))
.filter(a => !isNaN(a))
.sort()
.pop();
}
이 문제를 해결하는 가장 좋은 방법은 제 생각에 어떤 종류의 어떤 종류에 대한 규칙을 설정하는 것입니다. z-index
ES는 다른 종류의 요소에 사용됩니다. 그런 다음 올바른 것을 찾을 수 있습니다 z-index
문서를 되돌아 보면 사용합니다.
나는 당신이 관찰하는 것이 부두라고 생각합니다. 당신의 완전한 스타일 시트에 액세스하지 않으면 물론 나는 확실하게 말할 수 없습니다. 그러나 여기서 실제로 일어난 일이 당신이 배치 요소만이 z-index
.
또한, z-index
ES는 스타일 시트에서만 자동으로 할당되지 않으므로 다른 사람이 없습니다. z-index
에드 요소, z-index:1;
다른 모든 것의 위에있을 것입니다.
나는 당신이 직접해야한다고 생각합니다 ...
function findHighestZIndex()
{
var divs = document.getElementsByTagName('div');
var highest = 0;
for (var i = 0; i < divs .length; i++)
{
var zindex = divs[i].style.zIndex;
if (zindex > highest) {
highest = zindex;
}
}
return highest;
}
기본 속성이나 기타 항목은 없지만 모든 요소를 반복하여 알아내는 일부 자바스크립트를 작성할 수 있습니다.또는 jQuery와 같은 DOM 관리 라이브러리를 사용하는 경우 메소드를 확장하여(또는 이미 지원하는지 확인) 페이지 로드에서 요소 z-인덱스 추적을 시작한 다음 가장 높은 z-인덱스를 검색하는 것이 쉬워집니다. 색인.
사용자 스크립트 중 하나에서 사용하는 ECMAScript 6 구현을 추가하고 싶습니다. 나는 이것을 정의하기 위해 이것을 사용하고 있습니다 z-index
특정 요소 중에서 항상 가장 높은 것처럼 보입니다. 나는이 요소들을 사슬로 배제 할 수 있습니다 :not
선택자.
let highestZIndex = 0;
// later, potentially repeatedly
highestZIndex = Math.max(
highestZIndex,
...Array.from(document.querySelectorAll("body *:not([data-highest]):not(.yetHigher)"), (elem) => parseFloat(getComputedStyle(elem).zIndex))
.filter((zIndex) => !isNaN(zIndex))
);
하단 다섯 줄은 여러 번 실행되고 변수를 업데이트 할 수 있습니다. highestZIndex
반복적으로 현재의 highestZIndex
모든 요소의 값 및 기타 계산 된 Z- 색인. 그만큼 filter
모든 것을 제외합니다 "auto"
가치.
최근에 프로젝트 때문에 이 일을 해야 했는데, 그로부터 많은 혜택을 받았다는 것을 알았습니다. @필립 거버여기에 대한 훌륭한 답변이 있습니다. @flo의 훌륭한 답변(허용된 답변)입니다.
위에 언급된 답변과의 주요 차이점은 다음과 같습니다.
- CSS 둘 다
z-index
, 및 모든 인라인z-index
스타일이 계산되며, 비교 및 계산을 위해 둘 중 더 큰 스타일을 사용합니다. - 값은 정수로 강제 변환되며 모든 문자열 값(
auto
,static
, 등)은 무시됩니다.
여기 코드 예제의 CodePen이지만 여기에도 포함되어 있습니다.
(() => {
/**
* Determines is the value is numeric or not.
* See: https://stackoverflow.com/a/9716488/1058612.
* @param {*} val The value to test for numeric type.
* @return {boolean} Whether the value is numeric or not.
*/
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
/**
* Finds the highest index in the current document.
* Derived from the following great examples:
* [1] https://stackoverflow.com/a/1118216/1058612
* [2] https://stackoverflow.com/a/1118217/1058612
* @return {number} An integer representing the value of the highest z-index.
*/
function findHighestZIndex() {
let queryObject = document.querySelectorAll('*');
let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
let highest = 0;
childNodes.forEach((node) => {
// Get the calculated CSS z-index value.
let cssStyles = document.defaultView.getComputedStyle(node);
let cssZIndex = cssStyles.getPropertyValue('z-index');
// Get any inline z-index value.
let inlineZIndex = node.style.zIndex;
// Coerce the values as integers for comparison.
cssZIndex = isNumeric(cssZIndex) ? parseInt(cssZIndex, 10) : 0;
inlineZIndex = isNumeric(inlineZIndex) ? parseInt(inlineZIndex, 10) : 0;
// Take the highest z-index for this element, whether inline or from CSS.
let currentZIndex = cssZIndex > inlineZIndex ? cssZIndex : inlineZIndex;
if ((currentZIndex > highest)) {
highest = currentZIndex;
}
});
return highest;
}
console.log('Highest Z', findHighestZIndex());
})();
#root {
background-color: #333;
}
.first-child {
background-color: #fff;
display: inline-block;
height: 100px;
width: 100px;
}
.second-child {
background-color: #00ff00;
display: block;
height: 90%;
width: 90%;
padding: 0;
margin: 5%;
}
.third-child {
background-color: #0000ff;
display: block;
height: 90%;
width: 90%;
padding: 0;
margin: 5%;
}
.nested-high-z-index {
position: absolute;
z-index: 9999;
}
<div id="root" style="z-index: 10">
<div class="first-child" style="z-index: 11">
<div class="second-child" style="z-index: 12"></div>
</div>
<div class="first-child" style="z-index: 13">
<div class="second-child" style="z-index: 14"></div>
</div>
<div class="first-child" style="z-index: 15">
<div class="second-child" style="z-index: 16"></div>
</div>
<div class="first-child" style="z-index: 17">
<div class="second-child" style="z-index: 18">
<div class="third-child" style="z-index: 19">
<div class="nested-high-z-index">Hello!!! </div>
</div>
</div>
</div>
<div class="first-child">
<div class="second-child"></div>
</div>
<div class="first-child">
<div class="second-child"></div>
</div>
<div class="first-child">
<div class="second-child"></div>
</div>
</div>
jQuery를 사용하여:
요소가 제공되지 않으면 모든 요소를 확인합니다.
function maxZIndex(elems)
{
var maxIndex = 0;
elems = typeof elems !== 'undefined' ? elems : $("*");
$(elems).each(function(){
maxIndex = (parseInt(maxIndex) < parseInt($(this).css('z-index'))) ? parseInt($(this).css('z-index')) : maxIndex;
});
return maxIndex;
}
당신이 찾고 있다면 의 ID를 보여줍니다 모두 Z 지수가 가장 높은 요소:
function show_highest_z() {
z_inds = []
ids = []
res = []
$.map($('body *'), function(e, n) {
if ($(e).css('position') != 'static') {
z_inds.push(parseFloat($(e).css('z-index')) || 1)
ids.push($(e).attr('id'))
}
})
max_z = Math.max.apply(null, z_inds)
for (i = 0; i < z_inds.length; i++) {
if (z_inds[i] == max_z) {
inner = {}
inner.id = ids[i]
inner.z_index = z_inds[i]
res.push(inner)
}
}
return (res)
}
용법:
show_highest_z()
결과:
[{
"id": "overlay_LlI4wrVtcuBcSof",
"z_index": 999999
}, {
"id": "overlay_IZ2l6piwCNpKxAH",
"z_index": 999999
}]
훌륭한 아이디어에서 영감을 얻은 솔루션 @rajkeshwar prasad .
/**
returns highest z-index
@param {HTMLElement} [target] highest z-index applyed to target if it is an HTMLElement.
@return {number} the highest z-index.
*/
var maxZIndex=function(target) {
if(target instanceof HTMLElement){
return (target.style.zIndex=maxZIndex()+1);
}else{
var zi,tmp=Array.from(document.querySelectorAll('body *'))
.map(a => parseFloat(window.getComputedStyle(a).zIndex));
zi=tmp.length;
tmp=tmp.filter(a => !isNaN(a));
return tmp.length?Math.max(tmp.sort((a,b) => a-b).pop(),zi):zi;
}
};
#layer_1,#layer_2,#layer_3{
position:absolute;
border:solid 1px #000;
width:100px;
height:100px;
}
#layer_1{
left:10px;
top:10px;
background-color:#f00;
}
#layer_2{
left:60px;
top:20px;
background-color:#0f0;
z-index:150;
}
#layer_3{
left:20px;
top:60px;
background-color:#00f;
}
<div id="layer_1" onclick="maxZIndex(this)">layer_1</div>
<div id="layer_2" onclick="maxZIndex(this)">layer_2</div>
<div id="layer_3" onclick="maxZIndex(this)">layer_3</div>
Array.reduce ()
다음은 최상위를 결정하는 또 다른 해결책입니다 z-index
그것은 사용합니다 Array.reduce()
:
const max_zindex = [...document.querySelectorAll('body *')].reduce((accumulator, current_value) => {
current_value = +getComputedStyle(current_value).zIndex;
if (current_value === current_value) { // Not NaN
return Math.max(accumulator, current_value)
}
return accumulator;
}, 0); // Default Z-Index Rendering Layer 0 (Zero)
라이브러리로 사용할 수있는이 코드를 고려하십시오. getmaxzindex