我正在尝试一个javascript函数来修复向上滚动时的一部分标题。它工作得很好,但我想通过添加CSS3的过渡特性来使固定部件的运动平稳。我试过了,但没用。请求您的帮助plz.
window.onscroll = myFunction;
function myFunction() {
if(document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
document.getElementById("hdr_nav").style.position = "fixed";
} else {
document.getElementById("hdr_nav").style.position = "";
}
}//end function
*{margin: 0; padding: 0; box-sizing: border-box; -webkit-box-sizing: border-box; }
body {height: 3000px;}
.hdr_box {float: left; width: 100%; height: 65px; background: #eff1f2; position: relative; padding: 0; margin: 0;}
.hdr_box > .row1 {
float: left;
width: 100%;
height: 20px;
padding: 15px;
}
nav {
float: left;
width: 100%;
height: auto;
background: #e4e6e8;
position: relative;
transition: all 1s;
-webkit-transition: all 1s;
-moz-transition: all 1s;
}
nav ul {
list-style: none;
float: left;
width: 100%;
padding: 0;
margin: 0;
}
nav ul li {
float: left;
width: auto;
border-right: solid 1px #cacaca;
}
nav ul li a {
float: left;
width: auto;
padding: 16px;
text-align: center;
font-size: 14px;
}
<div class="hdr_box" id="hdr">
<div class="row1" id="hdr_row1"><h3>CompanyName</h3></div>
</div>
<nav id="hdr_nav">
<ul>
<li><a href="">About Us</a></li>
<li><a href="">Business</a></li>
<li><a href="">Our Work</a></li>
<li><a href="">Challenges</a></li>
</ul>
</nav>
这是因为您将position
属性从absolute
更改为fixed
,并且无法设置动画/转换。转换仅适用于具有单位的属性,例如px、rem、%或不透明度等。
但是,您可以使用关键帧动画修复它:
nav.is-fixed {
position: fixed;
animation: scroll .5s ease-out;
}
@keyframes scroll {
from {
transform: tranlateY(-100%);
}
to {
transform: tranlateY(0%);
}
}
如果需要,请确保前缀为@keyframes
和transform
。
对JS:做了一点改动
window.onscroll = myFunction;
function myFunction() {
var scrollAmount = document.body.scrollTop || document.documentElement.scrollTop;
var nav = document.getElementById("hdr_nav");
if(scrollAmount > 200) {
nav.classList.add('is-fixed');
} else {
nav.classList.remove('is-fixed');
}
}
https://jsfiddle.net/41nspon8/3/
添加新的CSS规则
.nav-fixed {
position: fixed;
-webkit-animation: slideInDown 450ms 1 ease-in-out;
}
@-webkit-keyframes slideInDown {
from {transform: translate(0%, -100%); }
to {transform: translate(0%, 0%); }
}
修改js代码
//document.getElementById("hdr_nav").style.position = "fixed";
document.getElementById("hdr_nav").classList.add("nav-fixed");
} else {
//document.getElementById("hdr_nav").style.position = "";
document.getElementById("hdr_nav").classList.remove("nav-fixed");
https://jsfiddle.net/13m8u7xm/