jQuery显示/隐藏不起作用

新手上路,请多包涵

我有一个带有一些 JS 和 CSS 的基本 html 页面:

 $('.expand').click(function() {
  $('.img_display_content').show();
});
 @charset "utf-8";

/* CSS Document */

.wrap {
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}

.img_display_header {
  height: 20px;
  background-color: #CCC;
  display: block;
  border: #333 solid 1px;
  margin-bottom: 2px;
}

.expand {
  float: right;
  height: 100%;
  padding-right: 5px;
  cursor: pointer;
}

.img_display_content {
  width: 100%;
  height: 100px;
  background-color: #0F3;
  margin-top: -2px;
  display: none;
}
 <html>

<head>
  <link href="beta.css" rel="stylesheet" type="text/css" />
  <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>

<body>
  <div class="wrap">
    <div class="img_display_header">
      <div class="expand">+</div>
    </div>
    <div class="img_display_content"></div>
  </div>
  </div>
</body>

</html>

单击 divexpand 什么都不做…我也尝试从 jQuery 网站复制/粘贴示例代码,但它也没有工作。谁能帮我解决这个问题?

原文由 Andras Mohacsi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 513
2 个回答

只需添加文档准备功能,这样它就等到 DOM 加载完毕,也可以使用 :visible 伪你可以编写一个简单的显示和隐藏函数。

样本

 $(document).ready(function(){

    $( '.expand' ).click(function() {
         if($( '.img_display_content' ).is(":visible")){
              $( '.img_display_content' ).hide();
         } else{
              $( '.img_display_content' ).show();
         }

    });
});

原文由 Jorge Y. C. Rodriguez 发布,翻译遵循 CC BY-SA 3.0 许可协议

演示

 $( '.expand' ).click(function() {
  $( '.img_display_content' ).toggle();
});
 .wrap {
    margin-left:auto;
    margin-right:auto;
    width:40%;
}

.img_display_header {
    height:20px;
    background-color:#CCC;
    display:block;
    border:#333 solid 1px;
    margin-bottom: 2px;
}

.expand {
 float:right;
 height: 100%;
 padding-right:5px;
 cursor:pointer;
}

.img_display_content {
    width: 100%;
    height:100px;
    background-color:#0F3;
    margin-top: -2px;
    display:none;
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="img_display_header">
<div class="expand">+</div>
</div>
<div class="img_display_content"></div>
</div>
</div>

http://api.jquery.com/toggle/

“显示或隐藏匹配的元素。”

这比使用 show() 和 hide() 方法的代码要短得多。

原文由 JohanVdR 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题