2 回答
![?](http://img1.sycdn.imooc.com/5333a2320001acdd02000200-100-100.jpg)
TA贡献1848条经验 获得超2个赞
这是可能的,但可能不会过于用户友好(毕竟,触摸屏没有“悬停”)。为此,您需要使用 JavaScript,并且可以执行以下操作:
// Get all 'hover' links
let hoverLinks = document.querySelectorAll('[data-scrollto]');
// Loop through, and add 'mouseenter' events
Array.from(hoverLinks).forEach(link => {
// Add hover state
link.addEventListener('mouseenter', () => {
// Find associated div
let div = document.getElementById(link.dataset.scrollto) || null;
// If div doesn't exist, return
if(!div) return;
// Scroll to div
div.scrollIntoView(true);
});
});
html,
body{
scroll-behavior: smooth;
}
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: #fff;
padding: 1em 0;
height: 1em;
line-height: 1em;
z-index: 2;
}
section {
height: 100vh;
box-sizing: border-box;
padding: 3em 0;
}
<nav>
<a href="home.html">Home</a>
<a href="books.html" data-scrollto="books-wrapper">Scroll to books</a>
</nav>
<section>
Hello
</section>
<section>
Hello
</section>
<section id="books-wrapper">
BOOKS!
</section>
<section>
Hello
</section>
<section>
Hello
</section>
简而言之,您只需要通过 JavaScript 添加一个事件侦听器(在本例中为“mouseenter”事件侦听器)到链接,当触发时(例如,当用户悬停在链接上时)将搜索关联的滚动位置并滚动到它。为了链接到页面,这可以通过标准<a href=""></a>链接来完成。
在上面的示例中,我使用 anid为滚动到位置创建唯一标识符,然后将其保存为链接中属性中的字符串。这样,您也可以重复使用此事件侦听器将滚动添加到其他链接。例如,您可以将一个idofcontact添加data-scrollto="contact"到页面上的另一个元素,并添加到一个新<a>标签以滚动它。
编辑:
为了使这更相关:
document.querySelector('.menu-button').addEventListener('mouseenter', () => {
let div = document.getElementById('books-home') || null;
if(!div) return;
div.scrollIntoView(true);
});
html,
body{
scroll-behavior: smooth;
}
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: #fff;
padding: 1em 0;
height: 1em;
line-height: 1em;
z-index: 2;
}
section {
height: 100vh;
box-sizing: border-box;
padding: 3em 0;
}
<nav>
<a href="home.html">Home</a>
<a href="books.html" class="menu-button">Scroll to books</a>
</nav>
<section>
Hello
</section>
<section>
Hello
</section>
<section id="books-home">
BOOKS!
</section>
<section>
Hello
</section>
<section>
Hello
</section>
添加回答
举报