كيف يمكنك معرفة أعلى مؤشر Z في المستند الخاص بك؟

StackOverflow https://stackoverflow.com/questions/1118198

  •  12-09-2019
  •  | 
  •  

سؤال

من أجل تعيين فحم يحتوي على صورة نصية شفافة كأعلى فهرس Z في وثيقتي، اخترت الرقم 10،000 وحل مشكلتي.

في السابق كنت قد خمنت مع الرقم 3 ولكن ليس لها أي تأثير.

لذلك، هل هناك طريقة علمية أكثر لمعرفة ما هو مؤشر Z أعلى من كل العناصر الأخرى الخاصة بك؟

حاولت البحث عن هذا المقياس في Firebug لكنه لم أستطع العثور عليه.

هل كانت مفيدة؟

المحلول

يمكنك الاتصال 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;
}

نصائح أخرى

سرقة بعض الكود من موقع Abcoder من أجل الوضوح:

  var maxZ = Math.max.apply(null, 
    $.map($('body *'), function(e,n) {
      if ($(e).css('position') != 'static')
        return parseInt($(e).css('z-index')) || 1;
  }));

باستخدام ES6 نهج نظافة

function maxZIndex() {

     return Array.from(document.querySelectorAll('body *'))
           .map(a => parseFloat(window.getComputedStyle(a).zIndex))
           .filter(a => !isNaN(a))
           .sort()
           .pop();
}

أفضل طريقة لحل هذه المشكلة هي، في رأيي، فقط لتعيين الاتفاقيات لنوع z-indexيتم استخدام وفاق لأنواع مختلفة من العناصر. ثم، ستجد الصحيح 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;
}

لا يوجد خاصية افتراضية أو أي شيء، ولكن يمكنك كتابة بعض جافا سكريبت للحلقة من خلال جميع العناصر ومعرفة ذلك. أو إذا كنت تستخدم مكتبة إدارة DOM مثل JQuery، فيمكنك تمديد أساليبها (أو معرفة ما إذا كان يدعمها بالفعل) بحيث يبدأ في تتبع عنصر Z-Directs من تحميل الصفحة، ثم يصبح تافدا لاسترداد أعلى فهرس.

أرغب في إضافة تطبيق 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" القيم.

اضطررت للقيام بذلك لمشروع مؤخرا، ووجدت أنني استفادت كثيرا من Philippe جربرإجابة رائعة هنا، و تضمين التغريدةإجابة رائعة (الإجابة المقبولة).

الاختلافات الرئيسية للإجابات المشار إليها أعلاه هي:

  • كل من CSS. z-index, وأي مضمن z-index يتم احتساب النمط، واستخدام أكبر من الاثنين للمقارنة والحساب.
  • يتم إكراه القيم إلى أعداد صحيحة، وأي قيم سلسلة (auto, static, ، إلخ) يتم تجاهلها.

هنا هو كود إصدارات مثال على التعليمات البرمجية، ولكنها مدرجة هنا أيضا.

(() => {
  /**
   * 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;
}

إذا كنت تتطلع إلى إظهار معرفات الكل عناصر مع أعلى مؤشرات 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 براساد .

	/**
	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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top