如何切换DIV元素的可见性

How can I toggle a the visibility of a DIV element?

本文关键字:可见性 元素 DIV 何切换      更新时间:2023-11-10

我正在尝试使用jQuery切换一个div元素,一个很好的例子是点击Udemy上的注册按钮。

我已经使用jQuery实现了类似的功能,但我确信为了获得我想要的效果,我必须使用JavaScript,但只是我不知道如何使用JavaScript。

我的实现可以在我的fiddle中看到,我最初将div设置为display:none,并使用jQuery在单击按钮时显示div
正如你可以用fiddle看到的那样,它显示的是一个放大的动画,而不是仅仅出现(不知道如何改变这一点),我只是无法通过再次单击按钮使div消失。

此外,我该如何通过单击屏幕上的任何位置来实现使div消失的功能?

感谢所有提前来帮助我的人。

您面临的问题是,单击按钮也是单击您希望弹出窗口消失的区域(如果已经显示)。由于事件冒泡,单击按钮会使弹出窗口出现,然后单击文档(由于冒泡而在此之后激发)会使弹出框立即消失。

要解决这个问题,您必须停止单击按钮,使其不会冒泡到文档的其余部分。你可以用

  event.stopPropagation();

因此,你需要做的是确保当点击按钮时,点击事件不会出现在文档中,你已经在文档中设置了一个点击事件处理程序,使弹出窗口消失:

 $(document).on('click', function(event) {
   // We want to hide the pop up, but not if you click on 
   // the pop up itself - - anywhere else, but not the pop up
   if(event.target.id !== "pop-up"){
      $('#pop-up').hide();
   }
 });

查看此小提琴的工作版本:https://jsfiddle.net/0ajpd9go/8/

如果您希望您的div只出现在屏幕上,请更改此行:

jQuery('#pop-up').toggle('fast');

到此:

jQuery('#pop-up').show();

也许你想试试引导模式:http://getbootstrap.com/javascript/#modals

我想您要找的是$.fn.toggle();
$.fn.toggle();切换元素的可见性,这意味着如果元素可见,则切换时它将被隐藏,如果元素被隐藏,则切换后它将被显示。

以下是使用toggle的基本(无动画)示例:

$(".button-that-toggles").on("click", function() {
  $(".div-to-toggle").toggle();
});

你的盒子切换为"放大动画",因为你使用了$.fn.slideToggle();

使用jQuery有三种默认切换方式(切换、音量切换和滑动切换)

以下是使用$.fn.fadeToggle();:切换元素的示例

$(".button-that-toggles").on("click", function() {
  // NOTE: 250 represents the duration of the animation, meaning that the animation will last 250 milliseconds.
  $(".div-to-toggle").fadeToggle(250);
});

以下是使用$.fn.slideToggle();:切换元素的示例

$(".button-that-toggles").on("click", function() {
  // NOTE: 250 represents the duration of the animation, meaning that the animation will last 250 milliseconds.
  $(".div-to-toggle").slideToggle(250);
});

这里还有一个例子,说明如何通过点击页面上的任何位置来隐藏div:

// listen for a click anywhere in the page
$(document).on("click", function(event) {
  // make sure the element that was clicked is not your div
  if(!$(event.target).is(".your-div")) {
    // you can now hide your div
    $(".your-div").hide();
  }
});

此外,请记住jQuery是JavaScript,事实上jQuery是一个用JavaScript编写的库。