javascript - 如何滚动到特定元素
问题描述
我尝试创建一种效果,当用户在英雄部分(使用 100vh)并向下滚动时,它会立即滚动到特定元素,当用户在该特定元素并向上滚动时,它会将他带到英雄部分
$(document).ready(function(){
$(window).scroll(function(){
var x = $("#scroll-to").offset();
var height1 = $("#scroll-to").outerHeight();
var y = document.documentElement.scrollTop;
var z = (x.top + height1) - y;
if(z < $(window).height()){
document.querySelector('#scroll-anchor').scrollIntoView({
behavior: 'smooth'
});
}
});
});
解决方案
使用 HTML id 和标签,并在链接中使用 id 作为 href
.blue{
background-color: blue;
min-width: 100px;
min-height:700px;
}
.red{
background-color: red;
min-width: 100px;
min-height:700px;
}
<a href="#red">red</a>
<div class="blue" id="blue"></div>
<div class="red" id="red"></div>
推荐阅读
- c# - Geckofx60.64 - 版本 60.0.26 无法在另一台 PC 上运行
- java - 将应用程序作为 JAR 运行时,本机库无法加载
- php - 如何使用 PHP 将日期输入到 mysql 数据库中
- git - 结帐合并请求分支而不添加远程
- java - 为什么我的方法显然不接受值?
- android - 通过电子邮件深层链接应用程序
- facebook-instant-games - SDK 问题我无法在虚拟主机中上传我的游戏
- python - 循环从两个列表创建数据帧
- javascript - Gatsby.js - 排版主题
- c# - 在 SWIGRegisterExceptionCallbacks_ 处遇到 SWIG 生成的代码挂起