首页 > 解决方案 > 如何滚动到特定元素

问题描述

我尝试创建一种效果,当用户在英雄部分(使用 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'
    });
             
        }
    });
});

标签: javascript

解决方案


使用 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>


推荐阅读