Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 修复平滑滚动问题_Javascript_Jquery_Html_Scroll_Smooth Scrolling - Fatal编程技术网

Javascript 修复平滑滚动问题

Javascript 修复平滑滚动问题,javascript,jquery,html,scroll,smooth-scrolling,Javascript,Jquery,Html,Scroll,Smooth Scrolling,我正在使用的简化版本: 我让滚动开始工作,但是,它不会从一个部分过渡到另一个部分。 示例:如果单击数字3,它将滚动到第三节。从这里开始,情况就是这样。 -单击数字2可返回第一节。 -单击数字4可进入第二节。 -再次单击数字3也会将您带回第一节。 这对所有部分都是一样的。 使用的jQuery代码: $('a[href*="#"]:not([href="#"])').click(function () { if (location.pathname.replace(/^\//, '') =

我正在使用的简化版本:

我让滚动开始工作,但是,它不会从一个部分过渡到另一个部分。

示例:如果单击数字3,它将滚动到第三节。从这里开始,情况就是这样。
-单击数字2可返回第一节。
-单击数字4可进入第二节。
-再次单击数字3也会将您带回第一节。

这对所有部分都是一样的。


使用的jQuery代码:

$('a[href*="#"]:not([href="#"])').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('#right').animate({ scrollTop: target.offset().top }, 1000);
            return false;
        }
    }
});

我把你的代码改了一点。它更简单,它可以帮助你理解正在发生的事情。我希望它能帮助你:

/*
1. I've changed the position fixed to position absolute on the #right element, the scroll won't work with position: fixed set
2. Added the on click event on the anchor tag this way I'm getting the href of the current clicked anchor by using $(this) and attr() method 
3. Added the e.preventdefault() to prevent the default action of the anchor element 
4. Doing the smooth scroll using the href got at 2 as id selector
*/
jQuery
代码如下所示:

$('#left a').on('click', function(e) {
  e.preventDefault();
  var id = $(this).attr('href');
  $('html, body').animate({
    scrollTop: $(id).offset().top
  }, 1000);
});
单击下面的按钮可以查看完整的工作代码段:

$('#左a')。在('click',函数(e){
e、 预防默认值();
var id=$(this.attr('href');
$('html,body')。设置动画({
scrollTop:$(id).offset().top
}, 1000);
});
html{
宽度:100%;
身高:100%;
}
身体{
宽度:100%;
身高:100%;
溢出:隐藏;
}
#左{
宽度:100%;
身高:100%;
背景色:#FFFFFF;
位置:固定;
排名:0;
左:0;
}
#对{
宽度:50%;
身高:100%;
背景色:#0000FF;
位置:绝对位置;
排名:0;
右:0;
z指数:1;
}
#一个{
身高:100%;
背景色:#FF0000;
}
#两个{
身高:100%;
背景色:#00FF00;
}
#三{
身高:100%;
背景色:#FFFF00;
}
#四{
身高:100%;
背景色:#00FFFF;
}
#五{
身高:100%;
背景色:#FF00FF;
}





一个 两个 三 四 五
非常感谢您。成功了!我能看到我的问题所在,谢谢你指出!