简体   繁体   English

使用 jQuery 切换 2 个元素的可见性

[英]Toggle visibility of 2 elements with jQuery

 function clickMe() { $('.hidden').toggle(); $('.visible').toggle(); }
 .hidden { visibility: hidden } .visible { visibility: visible }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class='hidden'>HiddenLabel</label> <label class='visible'>VisibileLabel</label> <button onClick='clickMe()'>Click me</button>

This works well for the visible label, but not for the hidden one, as it toggles the visbility of the 'VisibleLabel', but the visibility of the 'HiddenLabel' remains unchanged (hidden).这适用于可见标签,但不适用于隐藏标签,因为它会切换 'VisibleLabel' 的可见性,但 'HiddenLabel' 的可见性保持不变(隐藏)。

You are trying to swap the classes, and not the visibility.您正在尝试交换类,而不是可见性。 You should use .toggleClass :你应该使用.toggleClass

function clickMe() {
  $('.hidden, .visible').toggleClass("hidden visible");
}

Snippet片段

 function clickMe() { $('.hidden, .visible').toggleClass("hidden visible"); }
 .hidden { visibility: hidden } .visible { visibility: visible }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class='hidden'>HiddenLabel</label> <label class='visible'>VisibileLabel</label> <button onClick='clickMe()'>Click me</button>

The reason being, the function .toggle() alone can do the thing what you are trying to do, but now you need to toggle the classes and not the elements.原因是,单独的函数.toggle()可以做你想做的事情,但现在你需要切换类而不是元素。

The jQuery.toggle() changes the css-property display . jQuery.toggle()改变了 css-property display

And not the css-property visibility .不是css-property visibility

Try instead:试试吧:

.hidden {
    display: none;
}

.visible {
    display: block;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM