gpt4 book ai didi

javascript - window.location.hash向下滚动不平滑只能向左滚动

转载 作者:行者123 更新时间:2023-11-28 01:09:48 26 4
gpt4 key购买 nike

我已经实现了向左滚动以导航到完美运行的部分。现在我想在一个部分中添加 anchor ,这样如果您单击它们,它们就会在页面上顺利地向下滚动到其他 anchor 。我试图在现有函数中添加该功能,但无济于事。

我正在使用“jquery.easing.pack.js”。

在最初的版本中,我的 HTML 和 JS 如下所示:

<!-- scroll left to sections -->
<section id="1" class="section"></section>
<section id="2" class="section"></section>
<section id="3" class="section"></section>

<script type="text/javascript">
$(function() {
var $sections = $('section.section');

$sections.each(function() {
var $section = $(this);
var hash = '#' + this.id;

$('a[href="' + hash + '"]').click(function(event) {
$scrollElement.stop().animate({
scrollLeft: $section.offset().left
}, 1200, 'easeOutCubic', function() {
window.location.hash = hash;
});

event.preventDefault();
});
});

});
</script>

现在我有:

<!-- scroll left to sections -->
<section id="1" class="section">
<a class="scroll-down" href="#bottom-div">scroll down</a><!-- scroll down to div -->
<div id="bottom-div>here we go</div>
</section>
<section id="2" class="section"></section>
<section id="3" class="section"></section>

目前,如果我单击“向下滚动” anchor ,它将转到 bottom-div 但不顺利。所以我尝试添加另一个像这样的功能,但它不起作用......有什么想法如何让它工作,如果可能的话与我现有的功能一起工作?

$(function() {
var $bottomdivs = $('.scroll-down');

$bottomdivs.each(function() {
var $bottomdiv = $(this);
var hash = '#' + this.id;

$('a[href="' + hash + '"]').click(function(event) {
$scrollElement.stop().animate({
scrollTop: $bottomdiv.offset().top-100
}, 1200, 'easeOutCubic', function() {
window.location.hash = hash;
});

event.preventDefault();
});
});

});

最佳答案

通过设置哈希,我认为您正在调用标准 anchor 链接功能来跳转到该部分。尝试像这样自己处理滚动:

var $sections = $('section.section');

$sections.each(function() {
var $section = $(this);
var hash = '#' + this.id;

$('a[href="' + hash + '"]').click(function(event) {

$('body, html').animate({
scrollLeft: $section.offset().left
}, {queue:false, duration: 1200, easing: 'swing'});

$('body, html').animate({
scrollTop: $section.offset().top
}, {queue:false, duration: 1200, easing: 'swing', done: function () {
window.location.hash = hash;
}
});

});

event.preventDefault();
});

我在这里为你整理了一个 fiddle :http://jsfiddle.net/rjE4s/

我不确定 $scrollElement 是什么,因此我已将其从示例中删除。另外,我还更改了您的自定义缓动,因为我没有安装缓动包。你可以把它改回来。最后,我对动画进行了排队,以便左侧和顶部同时滚动,但您只需设置:

queue: true

在动画选项中,它会像原始函数一样对左侧和顶部进行动画处理。不确定您是否想要这个。

关于javascript - window.location.hash向下滚动不平滑只能向左滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24602993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com