[英]How do I get animation for my sticky navigation bar to work in both directions when scrolling?
感謝TylerH,當我向下滾動時,我已經設置了動畫集,但是當我向上滾動時 ,我希望該動畫能夠反轉。 我將假設我需要一個額外的javascript函數才能工作,所以暫時:
這是新的CSS(添加了.unfixed屬性):
sticknav {
background: #b50000;
height: 46px;
width: 1080px;
margin-right: 0px;
margin-left: 413px;
left: 0px;
right: 0px;
position: relative;
z-index: 9999;
border-bottom: 4px solid #e50000;
webkit-box-shadow: 0 2px 6px rgba(0,0,0,0.49);
box-shadow: 0 2px 6px rgba(0,0,0,0.49);
}
.fixed {
position:fixed;
animation: fill 333ms forwards ease-in-out;
-webkit-animation: fill 333ms forwards ease-in-out;
}
@keyframes fill {
from {margin-left: 413px; width: 1080px;}
to {margin-left: 0px; width: 100%;}
}
@-webkit-keyframes fill {
from {margin-left: 413px; width: 1080px;}
to {margin-left: 0px; width: 100%;}
}
.unfixed {
position:fixed;
animation: unfill 333ms ease-in-out;
-webkit-animation: unfill 333ms ease-in-out;
}
@keyframes unfill {
from {margin-left: 0px; width: 100%;}
to {{margin-left: 413px; width: 1080px;}
}
@-webkit-keyframes unfill {
from {margin-left: 0px; width: 100%;}
to {{margin-left: 413px; width: 1080px;}
}
以下是使用粘性導航的Javascript:
<script type="text/javascript">
$(document).ready(function() {
var aboveHeight = 205;
$(window).scroll(function(){
if ($(window).scrollTop() > aboveHeight){
$('sticknav').addClass('fixed').css('top','0').next().css('padding-top','60px');
} else {
$('sticknav').removeClass('fixed').next().css('padding-top','0');
}
});
});
</script>
我需要找到一種方法來激活.unfixed一次.fixed去激活,但這聽起來很復雜。 只有在用戶在.fixed激活后向上滾動后,我才需要激活它。 是的,這聽起來很復雜,任何幫助都會受到贊賞。 希望有一種更簡單的方法。 我想要的一個例子可以在Game Rebels上找到。
有一個簡單的解決方案來解決您的問題。 為了使用animation
並保留最終結果,而不是在完成時重置它,您需要應用animation-fill-mode
。
將動畫移動到.fixed
而不是.sticknav
(這將使動畫在向下滾動時添加.fixed
而不是在頁面加載時播放),並添加animation-fill-mode
:
.fixed {
position: fixed;
animation: fill 11s linear;
animation-fill-mode: forwards;
}
我還強烈建議您使用外部CSS文件,而不是將所有CSS放在<style>
標簽中。
嘗試下面的代碼並使用CSS transition
屬性而不是animation
,它看起來比animation
更簡單
stickynav{
background: #b50000;
height: 46px;
width: 1080px;
margin-right: 0px;
margin-left: 413px;
left: 0px;
right: 0px;
position: relative;
z-index: 9999;
border-bottom: 4px solid #e50000;
webkit-box-shadow: 0 2px 6px rgba(0,0,0,0.49);
box-shadow: 0 2px 6px rgba(0,0,0,0.49);
transition:width 500ms; //Add this
}
.fixed {
position:fixed;
margin-left:0px;
width:100%;
top:0px;
}
你js
將是:
$(window).scroll(function(){
if ($(window).scrollTop() > aboveHeight)
$('stickynav').addClass('fixed')
else
$('stickynav').removeClass('fixed')
});
工作方案
嘗試margin-left: 92px;
而不是margin-left: 413px
sticknav {
background: #b50000;
height: 46px;
width: 1080px;
margin-right: 0px;
margin-left: 92px;
left: 0px;
right: 0px;
position: relative;
z-index: 9999;
border-bottom: 4px solid #e50000;
webkit-box-shadow: 0 2px 6px rgba(0,0,0,0.49);
box-shadow: 0 2px 6px rgba(0,0,0,0.49);
animation-name: fill;
animation-duration: 12s;
}
產量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.