Svelte-隐藏并显示滚动导航



我希望导航隐藏向下滚动60px,并在向上滚动60px时显示,无论在页面的哪个部分。

我做了这个,但它是不完整的,我错过了什么?

<script>
let y = 0;
</script>
<svelte:window bind:scrollY="{y}" />
<nav class:hideNav={y > 60}>
<ul>
<li>link</li>
</ul>
</nav>
<style>
nav {
position: fixed;
top: 0;
}
.hideNav {
top: -70px;
}
</style>

滚动指定数量后,您的代码似乎完美地隐藏了导航栏,下面是代码的REPL。也许你的内容主体没有滚动?

这里是另一个实现REPL,它进一步阐述了如何使用滚动位置

<script>
import {onMount, onDestroy} from 'svelte'
const scrollNavBar = 60
let show = false
onMount(() => {
window.onscroll = () => {
if (window.scrollY > scrollNavBar) {
show = true
} else {
show = false
}
}
})

onDestroy(() => {
window.onscroll = () => {}
})
</script>
<style>
.scrolled {

transform: translate(0,calc(-100% - 1rem))
}

nav {
width: 100%;
position: fixed;
box-shadow: 0 -0.4rem 0.9rem 0.2rem rgb(0 0 0 / 50%);
padding: 10px;
transition: 0.5s ease

}
:global(body) {
margin: 0;
padding: 0;
height: 200vh;
}
</style>
<nav class:scrolled={show}>
elemnt
</nav>

在REPL中,导航似乎不会在向上滚动时重新出现。它只出现在页面的顶部。

例如,当用户在页面上的任何地方向上滚动30像素时,我也试图显示导航。我认为这也是OP所要求的。

我发现一个REPL成功地用jQuery完成了这项工作,但我目前正在努力使它在Svelte中工作。有线索吗?

如果我成功了,我会回头的。

// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();

// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;

// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('header').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('nav-up').addClass('nav-down');
}
}

lastScrollTop = st;
}

这里的答案对我没有帮助。所以这里有一个我在svelte:window中使用的REPL。我是怎么做到的;

  1. 创建一个变量,在滚动事件结束时存储滚动位置(在px中(-[我们称之为lastScrollPosition]

let lastScrollPosition = 0

  1. 滚动事件开始时;在svelte:window中,获取并比较当前滚动位置与我们在[1]中创建的最后一个滚动位置变量。(lastScrollPosition(

<svelte:window on:scroll={()=>{
var currentScrollposition = window.pageYOffset || document.documentElement.scrollTop; //Get current scroll position
if (currentScrollposition > lastScrollPosition) {
showNav = false
}else{ 
showNav = true
}
lastScrollPosition = currentScrollposition;
}}></svelte:window>

  1. 如果当前滚动位置大于lastScrollPosition,则showNav为false,否则为true。注意:您可以使用CSS或Svelte Conditional({#if}(来实现向下滚动时隐藏和向上滚动时显示(此示例显示CSS..(

<main>
<div class="nav {showNav == true? "show": "hide" }" >
Nav bar
</div>
<div class="content">
Content
</div>
</main>
<style>
.nav{
background-color: gray;
padding: 6px;
position: fixed;
top: 0;
width: 100%;
}
.content{
background-color: green;
margin-top: 25px;
padding: 6px;
width: 100%;
height: 2300px;
}
.hide{
display: none;
}
.show{
display: unset;
}
</style>

最新更新