gpt4 book ai didi

javascript - 查找容器中的所有可见元素

转载 作者:行者123 更新时间:2023-11-29 20:26:59 25 4
gpt4 key购买 nike

如何在某个容器中找到用户可见的所有元素?

也许存在某种只在可见区域搜索的querySelector

此外,如果 black_magic 返回最接近水平屏幕中心的元素,那将很好。

function black_magic( ) {
/* your code goes here */
};

button.onclick = function( ) {
const visible_elements = black_magic();
console.log( visible_elements );
};
:root {
background: linear-gradient( #e66465, #9198e5 );
}

button {
position: fixed;
top: 0.5rem;
}

#container {
display: flex;
flex-direction: column;
}

#container > section {
background: linear-gradient( #9198e5, #e66465 );
padding: 0.5rem;
text-align: center;
color: white;
font-size: xx-large;
margin: 1rem 0 1rem 0;
}
<html>
<head></head>
<body>
<button id=button>Check for Visible Elements in #container</button>
<section id=container>
<section>Hello, World! #01</section>
<section>Hello, World! #02</section>
<section>Hello, World! #03</section>
<section>Hello, World! #04</section>
<section>Hello, World! #05</section>
<section>Hello, World! #06</section>
<section>Hello, World! #07</section>
<section>Hello, World! #08</section>
<section>Hello, World! #09</section>
<section>Hello, World! #10</section>
<section>Hello, World! #11</section>
<section>Hello, World! #12</section>
<section>Hello, World! #13</section>
<section>Hello, World! #14</section>
<section>Hello, World! #15</section>
<section>Hello, World! #16</section>
</section>
</body>
</html>

最佳答案

这个灵魂可以解决问题。

function black_magic( ) {
const allElements = document.querySelectorAll('#container *');
let elements = [];
allElements.forEach(function(node){
let clientRect = node.getBoundingClientRect();
if (!(window.innerHeight <= clientRect.top || (clientRect.top <= 0 && clientRect.bottom <= 0)) ) {
elements.push(node);
}
});
return elements;
};

button.onclick = function( ) {
const visible_elements = black_magic();
console.log( visible_elements );
};
:root {
height: 2000px;
background: linear-gradient( #e66465, #9198e5 );
}

button {
position: fixed;
top: 0.5rem;
}

#test_element {
background: linear-gradient( #9198e5, #e66465 );
padding: 0.5rem;
text-align: center;
color: white;
font-size: xx-large;
margin-top: 1000px;
}
<html>
<head></head>
<body>
<button id=button>Check for Visible Elements in #container</button>
<section id=container>
<section id=test_element>
Hello, World!
</section>
</section>
</body>
</html>

参见: https://stackoverflow.com/a/18794913/6458608 , https://stackoverflow.com/a/3333352/6458608 :

关于javascript - 查找容器中的所有可见元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114868/

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