我们说我在数组中有3个对象:
var redBoxx=document.getElementById("redBox");
var blueBoxx=document.getElementById("blueBox");
var orangeBoxx=document.getElementById("orangeBox");
var shapeArray = [redBoxx, blueBoxx, orangeBoxx];
我想根据数据的当前可见性状态从数组中获取一个对象(如可见性:"隐藏"或"可见")。我该怎么做?
答案 0 :(得分:1)
您可以通过检查更改元素可见性的不同属性的计算值来执行此操作:
此处示例: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;
}
答案 1 :(得分:1)
在vanilla Javascript中没有“快速”的方法。你最好的选择是循环:
function visibleElementsIn(elements){
var output = [];
elements.forEach(function(element){
var visibility = window.getComputedStyle(element).visibility;
if(visibility === "visible"){
output.push(element);
}
});
return output;
}
答案 2 :(得分:1)
尝试使用以下内容
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>