Jquery平滑滚动只在内部工作

Jquery Smooth Scroll only working internally

本文关键字:在内部 工作 滚动 平滑 Jquery      更新时间:2023-09-26

我最近问了一个问题,在处理它之后…5个小时(不幸的是认真的),我能够顺利滚动到锚。这是我放入的js。

$(document).ready(function(e) {
$(".scroll").click(function(event){
     event.preventDefault();
     //calculate destination place
     var dest=0;
     if($(this.hash).offset().top > $(document).height()-$(window).height()){
          dest=$(document).height()-$(window).height();
     }else{
          dest=$(this.hash).offset().top;
     }
     //go to destination
     $('html,body').animate({scrollTop:dest}, 1000,'swing');
 });
});

我目前使用ID作为锚,但如果你想,我也可以切换到NAME。

这就是我想要的:这只适用于同一页面。我希望它能跨几页工作。

下面是我的例子:这个页面,应该加载这个页面,然后滚动到锚。

但是,它跳跃了。我应该在这段代码中添加什么?作为一个图形和html/css设计师,javascript对我来说是火箭科学。所以如果你能保持沉默我会很感激的。

坚持JS,并传递一个哈希属性:

<a href="http://something.com/some.php#start"> Go to page 2 ( Start ) </a>
<a href="http://something.com/some.php#goats"> Go to page 2 ( Goats ) </a>

并在page2

上使用简单的JS检查
<script>
    $(document).one("ready",function(){
        if( window.location.hash.length > 0 ){
             $("body, html").animate({scrollTop:$(window.location.hash).position().top},1000);
        }
    });
</script>

脚本将导致对象的ID为"start"(或ID为"goats")您可以在page2上定义目标,并向Yourdivision添加ID:

<div id="start"> Some content </div>
<div id="goats"> Goat content </div>