gpt4 book ai didi

javascript - 单页水平滚动 anchor (jQuery)

转载 作者:行者123 更新时间:2023-11-28 03:06:47 24 4
gpt4 key购买 nike

我正在尝试创建页面的水平滚动部分。

这是一个非常简单的概念,我以前做过很多次,所以我一定遗漏了一些相当明显的东西。

它似乎在每次点击的正确偏移之间交替。

$('a.scroll-trigger').click(function(e) {
var $this = $(this);
var $anchor = $($this.attr('href'));
var $container = $($this.attr('data-container'));
var offset = $anchor.offset().left;
$container.scrollLeft(offset);
e.preventDefault();
});
#pages {
overflow-x: hidden;
white-space: nowrap;
}

#pages>section {
display: inline-block;
width: 768px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
<li><a class="scroll-trigger" href="#section1" data-container="#pages">Section 1</a></li>
<li><a class="scroll-trigger" href="#section2" data-container="#pages">Section 2</a></li>
<li><a class="scroll-trigger" href="#section3" data-container="#pages">Section 3</a></li>
</ul>

<!-- pages is nested in a container with a maximum width of 768px. -->
<div id="pages">
<section id="section1">
<h2>Section 1</h2>
</section>
<section id="section2">
<h2>Section 2</h2>
</section>
<section id="section3">
<h2>Section 3</h2>
</section>
</div>

它不能正常工作。 offset 变量并不总是正确的。

有什么想法吗?

最佳答案

这是你要找的吗?

$('.scroll-trigger').each(function(index){
$(this).on('click',function(e) {
var $this = $(this);
var $anchor = $this.attr('href');
var $container = $this.attr('data-container');
var elem = $($anchor);
var offset = (elem.offset().left - elem.offsetParent().offset().left);

if(offset >= 0){
$($container).animate({'scrollLeft' : offset * index},200);
}else{
$($container).animate({'scrollLeft' : offset * -index},200);
}
e.preventDefault();
});
})
#pages{
position: relative;
overflow-x: hidden;
white-space: nowrap;
width: 100%;
border:1px solid #565656;
}
#pages>section {
display: inline-block;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a class="scroll-trigger" href="#section1" data-container="#pages">Section 1</a></li>
<li><a class="scroll-trigger" href="#section2" data-container="#pages">Section 2</a></li>
<li><a class="scroll-trigger" href="#section3" data-container="#pages">Section 3</a></li>
</ul>

<!-- pages is nested in a container with a maximum width of 768px. -->
<div id="pages">
<section id="section1">
<h2>Section 1</h2>
</section>
<section id="section2">
<h2>Section 2</h2>
</section>
<section id="section3">
<h2>Section 3</h2>
</section>
</div>

关于javascript - 单页水平滚动 anchor (jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45909771/

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