gpt4 book ai didi

javascript - 通过单击元素内的 anchor 或包含 div id 的任何位置将元素滚动到页面顶部

转载 作者:技术小花猫 更新时间:2023-10-29 12:06:39 28 4
gpt4 key购买 nike

我想将页面滚动到顶部,例如单击导航 div ID 内的任何链接或(如果可能)单击包含导航链接的 div ID 本身的任何位置时的导航 div ID。

我已经对此进行了研究,最接近的是 jQuery - How to scroll an anchor to the top of the page when clicked?但是由于某种原因,当我在我的示例中尝试这样做时,它似乎不起作用。我究竟做错了什么?

我是 jQuery 和 html 和 css 中的新手(并且使用了 div 的内联样式,因为我不想仅为示例提供单独的 css)。

当我从 jQuery - How to scroll an anchor to the top of the page when clicked? 加载 html 和脚本时在 Aptana 中它也不会滚动。即使在 div 类之上有一个内容 div,这样也有滚动的空间。

我在相关的 div 中包含了两个小段落来准确解释我的意思。

非常感谢任何帮助。谢谢。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>
$('#scroll_navigation ul li').click(function() {
$('html,body').animate({scrollTop: $(this).offset().top}, 800);
});
</script>

<body>

<div id="logo" style="margin: 0 auto; height: 300px; width: 60%; border: 1px solid #000">Logo</div>

<div id="scroll_navigation" style="margin: 0 auto; width: 40%; border: 4px solid #225599">

<p>Scroll navigation to top of page</p>
<p>Catch any clicks in "#scroll_navigation" to scroll the div id to the top of the page</p>


<div id="navigation">

<div class="container" style="margin: 0 auto; height: 220px; width: 60%; border: 1px solid #000">

<ul>
<p>Catch clicks on anchors to scroll the div id to the top of the page</p>
<li><a href="#Portfolio" title="">Portfolio</a></li>
<li><a href="#Services" title="">Services</a></li>
<li><a href="#About" title="">About</a></li>
<li><a href="#Contact" title="">Contact</a></li>
</ul>

</div>

</div>

</div>

<div id="content" style="margin: 0 auto; height: 1500px; width: 60%; border: 1px solid #000">Content</div>

</body>

编辑在 Firefox 中使用 scrollTop 时要注意这一点。 Animate scrollTop not working in firefox jQuery scrollTop - no support for negative values in Mozilla / Firefox我花了一段时间才弄清楚我的代码是好的,但 scrollTop 是 FF 中的这个问题。在同一示例中,也可以观察到该行为。当向下滚动并固定 anchor 时,FF 将向上滚动到目标 div 之前或之后 2-4px 的随机位置。

我现在正在使用 Scrolld.js 实现跨主要浏览器的像素完美滚动到所需的点。据我所知,我不明白不同的浏览器引擎如何从不同的(html 或正文)输入中呈现像 scrollTop 这样常见的东西,而且我是 jQuery 的新手。我猜这不是 jQuery 的“错误”,而是浏览器引擎如何呈现 scrollTop。

最佳答案

我不知道你有没有,但你必须包含 jquery 才能使用它。另一件事是,您的“点击监听器”必须在 jqueries 文档就绪函数中,如下所示:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>

$(document).ready(function(){
$('#scroll_navigation ul li').on('click', function(){
$('html,body').animate({scrollTop: $(this).offset().top}, 800);
});
});

</script>

关于javascript - 通过单击元素内的 anchor 或包含 div id 的任何位置将元素滚动到页面顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351563/

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