粘性菜单的平滑CSS动画

时间:2016-08-22 07:31:17

标签: css sticky

您好,

我有一个标题菜单,一旦用户开始向下滚动并且徽标从屏幕上升起就会粘在上面。菜单上的徽标也变小了。这是我的CSS代码:

//<![CDATA[
$(function(){
        // Check the initial Poistion of the Sticky Header
        var stickyHeaderTop = $('#logo').offset().top + 160;
 
        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#logo').addClass('fixed');
                } else {
                        $('#logo').removeClass('fixed');
                }
        });
  });//]]>
    #logo img {
        height: 145px;
        margin: 10px 0 0;
        transition: height 1s ease 0s;
    }
    .fixed img {
        height: 55px !important;
        position: fixed;
        top: 0;
        z-index: 3;
    }

main {height:1000px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="logo">
 <img alt="" src="https://www.gravatar.com/avatar/ca71f423aadaa366bd910dfcb1a25d0b?s=48&d=identicon&r=PG">
</div>
<main>
  some content
</main>

我有一个额外的jquery脚本负责将“fixed”类添加到DIV。

我的问题是,虽然徽标img的尺寸变化是平滑的,但定位不是因为徽标应该平滑下来,而是只是出现在原位。

我在这里缺少什么?

谢谢。

2 个答案:

答案 0 :(得分:0)

你有两个问题: 1)你只有动画高度。要为更多属性设置动画,只需在逗号后添加它们。

.selector {
    transition: height 250ms ease-in-out,
                top 250ms ease-in-out;
}

2)您试图为position: static; to position: fixed; top: 0;中的元素设置动画,但这不起作用,它需要始终保持静态(并使用负边距)或绝对所有时间(但即使标题未修复,您也必须设置&#34; top&#34;值。 我这样做:

#logo img {
    height: 145px;
    margin: 10px 0 0;
    transition: height 1s ease 0s,
                margin 1s ease 0s;
}
.fixed img {
    height: 55px !important;
    z-index: 3;
    margin: -155px 0 0;
}

答案 1 :(得分:0)

这是因为您使用的是id而不是class。所以基本上即使css属性发生变化,如果存在冲突,也会优先选择id选择器下的属性。因为,id优先于类。

另一个重要原因是因为你正在转换height,而不是转换位置。你希望它向下滑动(如果我理解的话)。没有成长,对吗?

检查此codepen。如果我理解你的要求,这应该有助于你理解这个问题。

//<![CDATA[
$(function() {
  // Check the initial Poistion of the Sticky Header
  var stickyHeaderTop = $('#logo').offset().top + 160;

  $(window).scroll(function() {
    if ($(window).scrollTop() > stickyHeaderTop) {
      $('#logo').addClass('fixed');
    } else {
      $('#logo').removeClass('fixed');
    }
  });
}); //]]>
.logo img{
  top:-200px;
  height: 145px;
  margin: 10px 0 0;
  transition: top .3s;
}

.fixed img {
  height: 55px !important;
  position: fixed;
  top: 0;
  z-index: 3;
  transition: top .3s;
}

main {
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="logo" class="logo">
  <img alt="" src="https://www.gravatar.com/avatar/ca71f423aadaa366bd910dfcb1a25d0b?s=48&d=identicon&r=PG">
</div>
<main>
  some content
</main>