(Jquery) 单击 div 以 css 过渡展开

(Jquery) On click div expands with css transition

我想在单击 div "arrow" 时扩展和减小 header 的高度。我试过用 Jquery 添加类,但它并没有真正起作用 HTML:

<header>
    <p>The title..</p>
    <h1>Some text</h1>
      <div class="arrow" id="arrow">
        <img src="img/arrow.svg" />
      </div>
</header>

CSS

header { 
  background: #2282A4;
  color: #fff;
  text-align: center;
  width: 100%;
  height: 450px;
  transition: height 0.5 ease;
}
expandheight {
  height: 850px;
}

JQuery:

$(document).ready(function() {
   $(function() {
      $('#arrow').click(function() {
         $('header').addClass('expandheight');
}); 
}); 
});

我不知道现在如何使用同一个按钮降低高度,在 "expandheight" class 处于活动状态时将其删除并在不活动时添加它...我已经试过if/else,我失败了。

您有多个语法错误:

  1. expandheight 的样式应使用 .expandheight
  2. 使用跨浏览器动画属性
  3. 使用toggleClass到add/removeclass

$(document).ready(function() {
  $(function() {
    $('#arrow').click(function() {
      $('header').toggleClass('expandheight');
    });
  });
});
header {
  background: #2282A4;
  color: #fff;
  text-align: center;
  width: 100%;
  height: 450px;      
  -webkit-transition:height 0.5s ease;
  -moz-transition:height 0.5s ease;
  transition:height 0.5s ease;
}

.expandheight {
  height: 850px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<header>
  <p>The title..</p>
  <h1>Some text</h1>
  <div class="arrow" id="arrow">
     <img src="img/arrow.svg" />
  </div>
</header>

如果要扩展和减小 header 的高度,请使用 toggleClass() 而不是使用 addClass()

jQuery(document).ready(function() {
    jQuery(function() {
        jQuery('#arrow').click(function() {
            jQuery('header').toggleClass('expandheight');
        });
    });
});

另外,您的代码中有一些错误。我创建了一个 jsfiddle 来向您展示它的工作原理。

https://jsfiddle.net/7yodz723/

(我在箭头周围加了一个边框,这样我们就可以清楚地看到示例在运行)

只需使用切换 class 即可切换 classes.

$(document).ready(function() {
  $(function() {
    $('#arrow').click(function() {
      $('header').toggleClass('expandheight');
  });
 });
});
header { 
  background: #2282A4;
  color: #fff;
  text-align: center;
  width: 100%;
  height: 450px;
  transition: height 0.5 ease;
}
.expandheight {
  height: 850px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<header>
  <p>The title..</p>
  <h1>Some text</h1>
  <div class="arrow" id="arrow">
     <img src="img/arrow.svg" />
  </div>
</header>