jQuery显示/隐藏不起作用

And*_*csi 21 html javascript css jquery

我有一个基本的HTML页面,包含一些JS和CSS:

$('.expand').click(function() {
  $('.img_display_content').show();
});
Run Code Online (Sandbox Code Playgroud)
@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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

点击div带有类的expand没有做任何事情......我也尝试从jQuery网站复制/粘贴示例代码,但它也没有用.任何人都可以帮我解决这个问题吗?

jyc*_*753 11

只需添加文件就绪功能,这种方式等待DOM加载,也可以通过使用:visible伪写入一个简单的显示和隐藏功能.

样品

 $(document).ready(function(){

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

    });
});
Run Code Online (Sandbox Code Playgroud)


Joh*_*VdR 5

演示版

$( '.expand' ).click(function() {
  $( '.img_display_content' ).toggle();
});
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/toggle/
“显示或隐藏匹配的元素。”

与使用show()和hide()方法相比,此代码要短得多。

  • 我保证OP的下一个问题是“当可见时如何将+更改为-” (4认同)