[英]Get Javascript object from an array based on it's CSS property
Let's say I have 3 objects in an array: 假设我在一个数组中有3个对象:
var redBoxx=document.getElementById("redBox");
var blueBoxx=document.getElementById("blueBox");
var orangeBoxx=document.getElementById("orangeBox");
var shapeArray = [redBoxx, blueBoxx, orangeBoxx];
I want to grab an object from the array based on it's current visibility status (as in visibility: "hidden" or "visible"). 我想根据数组的当前可见性状态(如可见性:“隐藏”或“可见”)从数组中获取一个对象。 How do I do that?
我怎么做?
You can do this by checking the computed value of the different properties that change an element's visiblity: 您可以通过检查改变元素可见性的不同属性的计算值来做到这一点:
Example here: https://jsfiddle.net/tt1s5mpm/ 此处的示例: 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;
}
There's not a "quick" way to do this in vanilla Javascript. 香草Javascript中没有“快速”方法来执行此操作。 Your best bet is with a loop:
最好的选择是循环:
function visibleElementsIn(elements){
var output = [];
elements.forEach(function(element){
var visibility = window.getComputedStyle(element).visibility;
if(visibility === "visible"){
output.push(element);
}
});
return output;
}
Try using something like below 尝试使用类似下面的内容
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.