jQuery:Javascript 中的隐藏选择器等效吗?

Sam*_*Sam 3 javascript ecmascript-6

我有这个代码;

$('.m-shop-top-product .b-item:hidden').slice(0, 10).show();
Run Code Online (Sandbox Code Playgroud)

我想将其转换为纯 Javascript,我无法找到等效的 Javascript 代码来返回所有隐藏的元素!我这样尝试过;

Array.from(document.querySelectorAll('.m-shop-top-product .b-item:hidden')).slice(0,10)
Run Code Online (Sandbox Code Playgroud)

但它给出的错误为;

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.m-shop-top-product .b-item:hidden' is not a valid selector.
Run Code Online (Sandbox Code Playgroud)

Ste*_*ger 5

嗯,根据jQuery 文档,隐藏选择器执行以下操作:

  • 它们的 CSS 显示值为 none。
  • 它们是 type="hidden" 的表单元素。
  • 它们的宽度和高度明确设置为 0。
  • 祖先元素被隐藏,因此该元素不会显示在页面上。

因此,您需要执行 document.querySelectorAll(".m-shop-top-product .b-item"),然后应用 filter(e) 来检查 css 样式“display”、表单隐藏属性、宽度、高度和循环遍历 element.parentElement 直到读取 documentElement,以查看父元素是否隐藏。

function isHidden(){ /* TODO: Implement */ return false;}

document.querySelectorAll(".m-shop-top-product .b-item").filter(function(e){
   return isHidden(e);
});
Run Code Online (Sandbox Code Playgroud)

例如

// 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')
}
Run Code Online (Sandbox Code Playgroud)

或者

function isVisible (ele) 
{
    var style = window.getComputedStyle(ele);
    return  style.width !== "0" &&
    style.height !== "0" &&
    style.opacity !== "0" &&
    style.display!=='none' &&
    style.visibility!== 'hidden';
}
Run Code Online (Sandbox Code Playgroud)

或者

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)
}
Run Code Online (Sandbox Code Playgroud)

或者

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;
}
Run Code Online (Sandbox Code Playgroud)