Detect if an element is visible
使用
我的HTML原样:
1 2 | Show Hide |
我的JS就是这样:
1 2 3 4 5 6 7 | function showTestElement(){ $('#testElement').fadeIn('fast'); } function hideTestElement(){ $('#testElement').fadeOut('fast'); } |
我想要的HTML:
1 | Show/Hide |
虽然纯jquery很好,但是我的JS和我想要的一样:
1 2 3 4 5 6 7 8 | function toggleTestElement(){ if (document.getElementById('testElement').***IS_VISIBLE***) { $('#testElement').fadeOut('fast'); } else{ $('#testElement').fadeIn('fast'); } } |
感谢您的帮助。
你在找:
1 | .is(':visible') |
尽管您可能会将选择器更改为使用jquery,但考虑到您仍然在其他地方使用它:
1 2 3 | if($('#testElement').is(':visible')) { // Code } |
需要注意的是,如果目标元素的任何一个父元素被隐藏,那么子元素上的
Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!
Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.
进一步扩展到您的特定用例,有一个内置的jquery函数,名为
1 2 3 | function toggleTestElement() { $('#testElement').fadeToggle('fast'); } |
不需要,只需在元素上使用
1 | $('#testElement').fadeToggle('fast'); |
这是一个演示。
1 2 3 | if($('#testElement').is(':visible')){ //what you want to do when is visible } |