使用. fadein()和. fadeout(),我一直在我的页面上隐藏/显示一个元素,但有两个按钮,一个用于隐藏,一个用于显示。现在我想用一个按钮来切换两者。
我的HTML / JavaScript,因为它是:
<a onclick="showTestElement()">Show</a>
<a onclick="hideTestElement()">Hide</a>
function showTestElement() {
$('#testElement').fadeIn('fast');
}
function hideTestElement() {
$('#testElement').fadeOut('fast');
}
我的HTML / JavaScript,因为我想拥有它:
<a onclick="toggleTestElement()">Show/Hide</a>
function toggleTestElement() {
if (document.getElementById('testElement').***IS_VISIBLE***) {
$('#testElement').fadeOut('fast');
} else {
$('#testElement').fadeIn('fast');
}
}
我如何检测元素是否可见?
你正在寻找:
.is(':visible')
尽管考虑到你在其他地方使用jQuery,你可能应该改变你的选择器:
if($('#testElement').is(':visible')) {
// Code
}
需要注意的是,如果目标元素的任何一个父元素是隐藏的,那么子元素上的.is(':visible')将返回false(这是有意义的)。
jQuery 3
:visible以很慢的选择器而闻名,因为它必须遍历DOM树来检查一堆元素。jQuery 3有个好消息,正如这篇文章所解释的(Ctrl + F表示:visible):
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内置了一个名为$.fadeToggle()的函数:
function toggleTestElement() {
$('#testElement').fadeToggle('fast');
}