簡體   English   中英

根據數組的CSS屬性從數組中獲取Javascript對象

[英]Get Javascript object from an array based on it's CSS property

假設我在一個數組中有3個對象:

var redBoxx=document.getElementById("redBox");
var blueBoxx=document.getElementById("blueBox");
var orangeBoxx=document.getElementById("orangeBox");

var shapeArray = [redBoxx, blueBoxx, orangeBoxx];

我想根據數組的當前可見性狀態(如可見性:“隱藏”或“可見”)從數組中獲取一個對象。 我怎么做?

您可以通過檢查改變元素可見性的不同屬性的計算值來做到這一點:

此處的示例: https : //jsfiddle.net/tt1s5mpm/

    function isVisible(el)
    {
       var styles = getComputedStyle( el );

       //Three different things are used for visibility
       if ( styles.getPropertyValue( "visibility" ) !== "hidden" &&
          styles.getPropertyValue( "display" ) !== "none" &&
          parseInt( styles.getPropertyValue( "opacity" ) ) !== 0 //You should really check all the versions like "-webkit-", etc
       )
       {
        return true;
       }

       return false;
    }

香草Javascript中沒有“快速”方法來執行此操作。 最好的選擇是循環:

function visibleElementsIn(elements){
  var output = [];
  elements.forEach(function(element){
    var visibility = window.getComputedStyle(element).visibility;
    if(visibility === "visible"){
      output.push(element);    
    }
  });
  return output;
}

嘗試使用類似下面的內容

 var redBox = document.getElementById('redBox'); var blueBox = document.getElementById('blueBox'); var orangeBox = document.getElementById('orangeBox'); var list = [redBox, blueBox, orangeBox]; Array.prototype.filterByProp = function(prop, value){ var currentStyle = window.getComputedStyle; return this.filter(function(el){return value === currentStyle(el,null)[prop]}); } //list.filter(function(el){return window.getComputedStyle(el,null).visibility === 'visible';}) console.log('hidden:' , list.filterByProp('visibility','hidden')); console.log('Visible:' , list.filterByProp('visibility','visible')); 
 div{ box-sizing:border-box; width:calc(100%/3); height: 50vh; border:1px solid #000; float:left; } #redBox{ background:#f00; } #blueBox{ background:#00f; visibility:hidden; } #orangeBox{ background:#f60; } } 
 <div id="redBox"> </div> <div id="blueBox"> </div> <div id="orangeBox"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM