Как вы можете определить самый высокий индекс z в вашем документе?
Чтобы установить div, содержащий прозрачное текстовое изображение как самый высокий z-индекс в моем документе, я выбрал номер 10 000, и он решил мою проблему.
Раньше я догадывался с номером 3, но это не имело никакого эффекта.
Итак, есть ли более научный способ выяснить, какой z-индекс выше, чем у всех ваших других элементов?
Я попытался найти эту метрику в Firebug, но не смог ее найти.
Ответы
Ответ 1
Вы можете вызвать findHighestZIndex
для определенного типа элемента, такого как "DIV", как это:
findHighestZIndex('div');
предполагая функцию 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;
}
Ответ 2
Кража кода с сайта abcoder для ясности:
var maxZ = Math.max.apply(null,
$.map($('body *'), function(e,n) {
if ($(e).css('position') != 'static')
return parseInt($(e).css('z-index')) || 1;
}));
Ответ 3
Использование ES6 более чистый подход
function maxZIndex() {
return Array.from(document.querySelectorAll('body *'))
.map(a => parseFloat(window.getComputedStyle(a).zIndex))
.filter(a => !isNaN(a))
.sort()
.pop();
}
Ответ 4
Не существует свойства по умолчанию или чего-то еще, но вы можете написать некоторый javascript для прокрутки всех элементов и определения его. Или, если вы используете библиотеку управления DOM, такую как jQuery, вы можете расширить свои методы (или узнать, поддерживает ли она ее уже), чтобы она начинала отслеживать z-индексы элементов из загрузки страницы, а затем становится тривиальной для получения наивысшего z- индекс.
Ответ 5
Лучший способ решить эту проблему - это, на мой взгляд, просто установить собственные соглашения о том, какие типы z-index
es используются для разных типов элементов. Затем вы найдете правильный z-index
для использования, просмотрев документацию.
Ответ 6
Я верю, что вы наблюдаете за Вуду. Без доступа к вашей полной таблице стилей я, конечно, не могу сказать надежно; но мне кажется вероятным, что на самом деле произошло то, что вы забыли, что только позиционированные элементы затронуты z-index
.
Кроме того, z-index
es не назначаются автоматически, только в таблицах стилей, что означает, что без других z-index
ed элементов z-index:1;
будет поверх всего остального.
Ответ 7
Я думаю, вы должны сделать это сами...
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;
}
Ответ 8
Я хотел бы добавить свою реализацию 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
значения highestZIndex
и всеми другими вычисленными z-индексами всех элементов. filter
исключает все "auto"
значения.
Ответ 9
Мне пришлось сделать это для проекта в последнее время, и я обнаружил, что здесь я очень много выиграл от @Philippe Gerber и @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>
Ответ 10
Использование 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;
}
Ответ 11
Решение, вдохновленное великолепной идеей @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>
Ответ 12
Если вы хотите показать идентификаторы всех элементов с самыми высокими 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
}]
Ответ 13
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)
Ответ 14
Рассмотрим этот код, который вы можете использовать в качестве библиотеки: getMaxZIndex