18

单击按钮时显示 div 然后用关闭按钮隐藏它的最佳方法是什么?

我的 Jquery 代码如下:

$(".imageIcon").click(function(){
$('.imageShowWrapper').css("visibility", 'visible');
});
 $(".imageShowWrapper").click(function(){
$('.imageShowWrapper').css("visibility", 'hidden');
});

除了我遇到的问题是它会自动关闭而无需任何点击。它加载一切正常,显示约 1/2 秒,然后关闭。有任何想法吗?

4

6 回答 6

25

您可以使用showhide方法:

$(".imageIcon").click(function() {
    $('.imageShowWrapper').show();
});

$(".imageShowWrapper").click(function() {
    $(this).hide();
});
于 2012-05-01T02:53:45.990 回答
5

According to your requirement, I believe what you need is as simple as this: http://jsfiddle.net/linmic/6Yadu/

However, using the visibility is different from using show/hide function, gory details: What is the difference between visibility:hidden and display:none?

于 2012-05-01T03:30:03.033 回答
2

另外的选择:

$(".imageIcon, .imageShowWrapper").click(function() {  
    $(".imageShowWrapper").toggle($(this).hasClass('imageIcon'));     
});

您还可以使用fadeToggleslideToggle

于 2012-05-01T03:15:26.113 回答
0
$(".imageIcon, .imageShowWrapper").click(function(){
    $('.imageShowWrapper').toggle();
});
于 2012-05-01T03:14:49.817 回答
0

您将使用淡入淡出方法获得更平滑的过渡:

var imageIcon = $(".imageIcon"),
    imageShowWrapper = $(".imageShowWrapper");

imageIcon.on("click", function(){
  imageShowWrapper.stop().fadeIn();
});

imageShowWrapper.on("click", function(){
   $(this).stop().fadeOut();
});

演示:http: //jsbin.com/uhapom/edit#javascript,html,live

于 2012-05-01T02:54:20.627 回答
0

很难说没有看到代码的 html 和 jquery 部分。但是,看起来您显示/隐藏 div 的部分受到页面重新加载的影响?您可能正在将显示/隐藏 div 的代码放在一个$(document).ready(function() { .....})块内。此外,另一个需要注意的相关点是,每当单击按钮、锚点等 html 元素时,单击被认为是默认类型 = 提交,并且在这种情况下页面也会重新加载。要停止这种情况,可以使用event.preventDefault()

于 2019-01-16T01:31:48.593 回答