问题
If I list for example document.body.children
I get some elements that can be shown on the screen (like <div>
) and some that can not be shown (like <script>
).
Is there a (future) safe way to find out if an element can be shown on the screen?
回答1:
All elements are "viewable":
<style> * { display: block; } </style>
<script> // even scripts </script>
So either check if they are currently visible, by checking their computed style (I'll let you decide which properties you should check since even "visible" can have several interpretations), or use a list of known elements that are usually not rendered.
回答2:
The future may change in terms of other methods available but currently you could simply exclude the script by doing:
elements = Array.from(document.body.children).map(item => item.tagName != 'SCRIPT')
Add conditions for other types you want to exclude until you reach your desired 'viewable' collection.
来源:https://stackoverflow.com/questions/64493499/how-do-i-see-if-a-htmlelement-is-of-a-viewable-kind