gpt4 book ai didi

javascript - jQuery :hidden selector equivalent in Javascript?

转载 作者:行者123 更新时间:2023-11-30 13:50:22 25 4
gpt4 key购买 nike

我有这个代码;

$('.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 docs ,隐藏的选择器执行以下操作:

  • 它们的 CSS 显示值为 none。
  • 它们是 type="hidden"的表单元素。
  • 它们的宽度和高度明确设置为 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;
}

关于javascript - jQuery :hidden selector equivalent in Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58375997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com