嗨,
我有一个标题菜单,一旦用户开始向下滚动并且徽标从屏幕上移开,它就会粘在顶部。菜单上的标识也变小了。这是我的 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 脚本,负责将“固定”类添加到 DIV。
我的问题是,虽然徽标 img 的大小变化是平滑的,但定位不是这样,因为徽标应该平滑地下降,而不是它只是出现在适当的位置。
我在这里错过了什么?
谢谢。
你有两个问题: 1)您只对高度进行了动画处理。要为更多属性设置动画,只需在逗号后添加它们。
.selector {
transition: height 250ms ease-in-out,
top 250ms ease-in-out;
}
2)您正在尝试为
position: static; to position: fixed; top: 0;
中的元素设置动画,但这不起作用,它需要始终保持静态(并以负边距工作)或始终保持绝对(但您将拥有即使标题不固定,也可以设置“最高”值。
我会这样做:
#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;
}
这是因为您使用的是
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>