[英]jQuery :hidden selector equivalent in Javascript?
我有這個代碼;
$('.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 文檔,隱藏選擇器執行以下操作:
所以,你會做一個 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;
}
我確實喜歡這個;
const allProducts = Array.from(document.querySelectorAll('.m-shop-top-product .b-item'));
const showMoreButton = document.querySelectorAll('.m-shop-top-product .show-more button')[0];
showMoreButton.addEventListener('click', () => {
const hiddenProducts = allProducts.filter((el)=>{
return el.style.display === '';
});
hiddenProducts.slice(0, 10).forEach(el => {
el.style.display = 'block';
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.