我有这个代码;
$('.m-shop-top-product .b-item:hidden').slice(0, 10).show();
我想将其转换为纯Javascript,我找不到等效的Javascript代码,这些代码返回我所有隐藏的元素! 我试过这样;
Array.from(document.querySelectorAll('.m-shop-top-product .b-item:hidden')).slice(0,10)
但它给出的错误是;
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.m-shop-top-product .b-item:hidden' is not a valid selector.
好吧,根据jQuery文档,隐藏选择器执行以下操作:
- 它们的 CSS 显示值为 none。
- 它们是类型="隐藏"的表单元素。
- 它们的宽度和高度显式设置为 0。
- 祖先元素是隐藏的,因此该元素不会显示在页面上。
所以,你会做一个document.querySelectorAll(".m-shop-top-product.b-item"( 然后应用 filter(e( 检查 CSS 样式"显示",形成隐藏属性、宽度、高度,并循环遍历 element.parentElement,直到您读取 documentElement,以查看父级是否隐藏。
function isHidden(){ /* TODO: Implement */ return false;}
document.querySelectorAll(".m-shop-top-product .b-item").filter(function(e){
return isHidden(e);
});
例如
// Where el is the DOM element you'd like to test for visibility
function isHidden(el)
{
var style = window.getComputedStyle(el);
return (style.display === 'none')
}
或
function isVisible (ele)
{
var style = window.getComputedStyle(ele);
return style.width !== "0" &&
style.height !== "0" &&
style.opacity !== "0" &&
style.display!=='none' &&
style.visibility!== 'hidden';
}
或
function isVisible(el)
{
// returns true iff el and all its ancestors are visible
return el.style.display !== 'none' && el.style.visibility !== 'hidden'
&& (el.parentElement? isVisible(el.parentElement): true)
}
或
function isHidden(el)
{
if(!el)
return false;
do
{
if(!(el instanceof Element))
continue;
var style = window.getComputedStyle(el);
if (style.width == "0" || style.height == "0" || style.opacity == "0" || style.display == "none" || style.visibility == "hidden")
{
return true;
}
// console.log(el);
} while ((el = el.parentNode));
return false;
}