如何基于最高Z索引获取元素属性

时间:2018-07-30 19:38:09

标签: javascript

我不知道该如何实现,我有一些具有common_class类名的元素,我想获得最高z-index元素的ID,有可能吗?

function findHighestZIndex(elem)
{
  var elems = document.getElementsByClassName(elem);
  var highest = 0;
  for (var i = 0; i < elems.length; i++)
  {
    var id = document.getElementsByClassName(elem); 
    id.getAttribute("id");
console.log(id);
    var zindex=document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("z-index");
    var ElementDisplay = document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("display");
    if ((zindex > highest) && (zindex != 'auto') && (ElementDisplay == 'block'))
    {
      highest = zindex;
    }

}

4 个答案:

答案 0 :(得分:3)

这是getHighest(selector)函数的简短有效实现,以及使用该函数检索id值的示例代码段(单击框以增加其z索引)。

(重要的部分是前三个功能;如果需要,可以将它们压缩为一个功能。)

function getHighest(selector) {
  // Return the element that matches selector having the largest z index
  return Array.from(document.querySelectorAll(selector)).reduce((a, b) => getZIndex(a) >= getZIndex(b) ? a : b);
}

function getZIndex(el) {
  // Return the z-index of el, or 0 if none is set.
  return parseInt(getCssProperty(el, "z-index")) || 0;
}

function getCssProperty(el, prop) {
  // Return the computed value of the css property prop for the element el
  return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
}


// -------------------------------------------------------------------------
// additional code for demo below
// -------------------------------------------------------------------------


function updateHighest() {
  let highest = getHighest(".box");
  document.querySelector("#highest").textContent = `#${highest.id} (${getZIndex(highest)})`;
  document.querySelector("#highest").style.color = getCssProperty(highest, "background-color");
}

function setContentToZIndex(el) {
  el.textContent = getZIndex(el);
}

Array.from(document.querySelectorAll(".box")).forEach(b => {
  b.onclick = () => {
    b.style.zIndex = getZIndex(b) + 1;
    setContentToZIndex(b);
    updateHighest();
  };
  setContentToZIndex(b);
  updateHighest();
});
.box {
  width: 100px;
  height: 100px;
  display: block;
  background: grey;
  position: absolute;
  color: white;
  font-size: 2rem;
  text-align: center;
  line-height: 100px;
  user-select: none;
  font-family: sans-serif;
}

#b1 {
  background: #ff268a;
  left: 0px;
  top: 0px;
}

#b2 {
  background: #242792;
  left: 50px;
  top: 50px;
}

#b3 {
  background: #0ac3d6;
  left: 25px;
  top: 75px;
}

p {
  margin-left: 200px;
  font-family: sans-serif;
  font-size: 1.2rem;
}
<div class="box" id="b1"></div>

<div class="box" id="b2"></div>

<div class="box" id="b3"></div>

<p>highest z-index: <span id="highest"></span></p>

答案 1 :(得分:1)

如果您指的是不在此处获取id值:

var elems = document.getElementsByClassName(elem);
var highest = 0;
  for (var i = 0; i < elems.length; i++)
  {
      //This is all wrong here, commenting it out
      //var id = document.getElementsByClassName(elem); //You already have this collection
      //id.getAttribute("id"); //The above returns a collection so this would fail, you'd need to use an index of the collection
      //console.log(id);

      //You already have the elements you want, just use the i index to grab the element
      //and it's id
      console.log(elems[i].id);

答案 2 :(得分:1)

您可以修改函数以返回具有最高z-index的元素,然后仅使用.id来获取其id

另一个问题:您正在将zindexhighest作为字符串而不是数字进行比较。如您的示例所示,如果要比较zindex的z索引和{{1}的z索引,那么在比较之前,我已经用一元+前缀9 }},它会认为1000更大。

示例:

9
function findHighestZIndex(elem) {
  var highest = 0;
  var highestElement = null;
  var elems = document.getElementsByClassName(elem);

  for (var i = 0; i < elems.length; i++) {
    var style = document.defaultView.getComputedStyle(elems[i], null);
    var zindex = style.getPropertyValue("z-index");
    var ElementDisplay = style.getPropertyValue("display");

    if ((zindex != 'auto') && (+zindex > highest) && (ElementDisplay == 'block')) {
      highest = zindex;
      highestElement = elems[i];
    }
  }

  return highestElement;
}

var elem = findHighestZIndex("zindex");
console.log(elem.id + " has the highest z-index.");
div.zindex {
  z-index: 500;
  position: absolute;
  display: block;
}

答案 3 :(得分:0)

您可以使用以下功能:

 function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
 }
function findHighestZIndex(className) {
let queryObject = document.getElementsByClassName(className);
let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
let highest = 0;
var highestElem;

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;
    highestElem = node;
  }
});
var obj = {highestZIndex: highest, elem: highestElem};
 return obj;
}  

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<html>
<body>
<div class="test" style="z-index: 100;" id="x">1</div>
<div class="test" style="z-index: 10;">2</div>
<div class='test' id="test">3</div>
<script>
function isNumeric(val) {
    return !isNaN(parseFloat(val)) && isFinite(val);
  }
function findHighestZIndex(className) {
    let queryObject = document.getElementsByClassName(className);
    let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
    let highest = 0;
    var highestElem;
    
    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;
        highestElem = node;
      }
    });
    var obj = {highestZIndex: highest, elem: highestElem};
    return obj;
  }
 console.log(findHighestZIndex('test').elem.id);
</script>
</body>
</html>

</body>
</html>