Is it possible to detect element visibility in CSS?
P粉316423089
2023-08-22 22:28:55
<p>I looked through the API, looking for some pseudo-selectors such as <code>:visible</code> or <code>:hidden</code>, but was disappointed to find that no such selector existed. Since jQuery has supported these selectors for a while, I hope they will be implemented. My idea is that I only want to show a specific element when the element next to it is hidden, but I don't want to use JavaScript to do that. Are there any options? </p>
It depends on what you mean by "next to it". You can use Attribute selectors to select elements by visibility. Or choose from here:
To access an element by visibility, you can use e.g. the substring matching attribute selector asterisk
[att*=val]
. Assume that the div style is hidden usingvisibility: hidden;
:The question now is how to access the "next to it" element. If the element you are trying to target is directly behind a hidden element (within the same parent), use the selector:
If it's before, there's nothing you can do about it, but look for some workarounds in the answers to this question: Is there a "previous sibling" CSS selector?
No, that's not possible, it's not possible, at least not in a stylesheet.
Otherwise, you will create an infinite loop:
Theelement starts out visible, then the selector selects it and hides it, then the selector doesn't apply, it becomes visible again, and so on.
In JS API, pseudo-class selectors are allowed, such as
querySelector
. But as far as I know, there is no such thing yet, and it's not possible to implement using only CSS.