首页 > 解决方案 > CSS过渡高度属性不起作用

问题描述

我正在尝试平滑地转换我的#superheader 元素的高度,但是出了点问题。我的登台站点在这里。我能够使用下面的代码片段使其正常工作,但似乎有些东西在翻译中丢失了。有任何想法吗?

jQuery(document).ready(function($){
  // hiding superheader after scrolling a little ways
  $( window ).scroll(function() {
    var cutoff = 70;
    if ($(window).scrollTop()>200) {
      $("#superheader").addClass('hide');
    }
    if ($(window).scrollTop()<200) {
      $("#superheader").removeClass('hide');
    }
  })
})
#superheader {
    background-color: red;
    z-index: 700;
    box-shadow: none;
    padding: 20px 25px;
        width:100%;
        display:flex;
        transition: all .4s;
        height:80px;
  position:fixed;
  top:0;
}

 #superheader.hide {
    height:20px;
    padding:0;
    overflow: hidden;
}

#page {
  height:1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='superheader'></div>
<div id='page'></div>

标签: jquerycss

解决方案


正如@showdev 评论,问题是因为hide您的主题中添加了样式display:none,并且它破坏了动画。你所能做的就是:

  1. 更改班级(例如从.hideto .hidden

jQuery(document).ready(function($){
  // hiding superheader after scrolling a little ways
  $( window ).scroll(function() {
    var cutoff = 70;
    if ($(window).scrollTop()>200) {
      $("#superheader").addClass('hidden');
    }
    if ($(window).scrollTop()<200) {
      $("#superheader").removeClass('hidden');
    }
  })
})
#superheader {
    background-color: red;
    z-index: 700;
    box-shadow: none;
    padding: 20px 25px;
        width:100%;
        display:flex;
        transition: all .4s;
        height:80px;
  position:fixed;
  top:0;
}

 #superheader.hidden {
    height:20px;
    padding:0;
    overflow: hidden;
}

#page {
  height:1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='superheader'></div>
<div id='page'></div>

  1. 或使用相同的类,但只是!important在显示上添加,就像这样

jQuery(document).ready(function($){
  // hiding superheader after scrolling a little ways
  $( window ).scroll(function() {
    var cutoff = 70;
    if ($(window).scrollTop()>200) {
      $("#superheader").addClass('hide');
    }
    if ($(window).scrollTop()<200) {
      $("#superheader").removeClass('hide');
    }
  })
})
#superheader {
    background-color: red;
    z-index: 700;
    box-shadow: none;
    padding: 20px 25px;
        width:100%;
        display:flex !important; /* add this */
        transition: all .4s;
        height:80px;
  position:fixed;
  top:0;
}

 #superheader.hide {
    height:20px;
    padding:0;
    overflow: hidden;
}

#page {
  height:1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='superheader'></div>
<div id='page'></div>


推荐阅读