当出现“固定菜单”时,如何插入平滑过渡?
我正在使用属性transition
,但它无效。
我做错了什么?
window.addEventListener("scroll", function(event) {
var scrollPos;
var menu_mobile = document.getElementById("menu_mobile");
scrollPos = window.scrollY;
if(scrollPos > 108){
menu_mobile.style.display = "initial";
menu_mobile.style.transform = "translateY(0%)";
menu_mobile.style.top = "0";
menu_mobile.style.transition = "all 0.3s";
}
if(scrollPos < 108){
menu_mobile.style.display = "none";
}
}, false);
.menu-mobile{
display: none;
width: 100%;
position: fixed;
background: #ff008a;
z-index: 99;
transform: translateY(-240%);
transition: all 0.3s;
-webkit-transition: all 0.3s;
}
.aux{
height: 1500px;
background: gray;
}
<section class="menu-mobile container no-margin" id="menu_mobile">
<div class="col-md-12 text-center no-margin">
<h2 class="titulo-menu-mobile">TEXT TEXT TEXT</h2>
</div>
</section>
<section class="aux"></section>
答案 0 :(得分:1)
您不能transition
display
财产。您希望使用opacity
,但此可能会根据页面布局的其余部分创建布局问题,因为opacity: 0;
的元素仍将占用页面上的空间。
window.addEventListener("scroll", function(event) {
var scrollPos;
var menu_mobile = document.getElementById("menu_mobile");
scrollPos = window.scrollY;
if(scrollPos > 108){
menu_mobile.style.opacity = "1";
menu_mobile.style.transform = "translateY(0%)";
menu_mobile.style.top = "0";
menu_mobile.style.transition = "all 0.3s";
}
if(scrollPos < 108){
menu_mobile.style.opacity = "0";
}
}, false);
&#13;
.menu-mobile{
opacity: 0;
width: 100%;
position: fixed;
background: #ff008a;
z-index: 99;
transform: translateY(-240%);
transition: all 0.3s;
-webkit-transition: all 0.3s;
}
.aux{
height: 1500px;
background: gray;
}
&#13;
<section class="menu-mobile container no-margin" id="menu_mobile">
<div class="col-md-12 text-center no-margin">
<h2 class="titulo-menu-mobile">TEXT TEXT TEXT</h2>
</div>
</section>
<section class="aux"></section>
&#13;
这里的相同代码在菜单出现时清理并切换类,而不是手动应用javascript更改。浏览器中唯一可见的区别是,当您在菜单已经滑落一次后向上/向下滚动时,此技术将translateY()
菜单,并且您的原始代码没有这样做。
window.addEventListener("scroll", function(event) {
var scrollPos = window.scrollY,
menu_mobile = document.getElementById("menu_mobile"),
threshold = 108;
if (scrollPos > threshold) {
menu_mobile.classList.add('open');
} else {
menu_mobile.classList.remove('open');
}
}, false);
&#13;
.menu-mobile {
opacity: 0;
width: 100%;
position: fixed;
background: #ff008a;
z-index: 99;
transform: translateY(-100%);
transition: all 0.3s;
-webkit-transition: all 0.3s;
}
.open {
opacity: 1;
transform: translateY(0);
top: 0;
}
.aux {
height: 1500px;
background: gray;
}
&#13;
<section class="menu-mobile container no-margin" id="menu_mobile">
<div class="col-md-12 text-center no-margin">
<h2 class="titulo-menu-mobile">TEXT TEXT TEXT</h2>
</div>
</section>
<section class="aux"></section>
&#13;