gpt4 book ai didi

javascript - 单击链接滚动到元素然后向元素添加一个类

转载 作者:行者123 更新时间:2023-11-30 10:24:22 24 4
gpt4 key购买 nike

我有这个 html 标记:

<div id="main">
<p>some text</p>
<a id="goto-notes" href="#">see notes</a>
<p>some text...</p>
<div id="notes">
<p>notes here</p>
</div>
</div>

现在我想在单击 a#goto-notes 时滚动到 div#notes,然后向 div#notes 添加一个类(已看到)以更改样式。我以前使用 jquery scrollTo 来轻松完成它,但现在我想知道如何在没有 scrollTo 或任何插件的情况下做到这一点。我已经做了一些研究,这就是我到目前为止得到的结果。

$('#goto-notes').click(function(){
$('#main').animate({scrollTop:500},'slow');
$('#notes').addClass('seen');
});

目前 div#notes 位于链接下方 500px+ 处。

  1. 如何在不指定 500 的情况下自动定位它,类似于 scrollTo => $('#main').scrollTo('#notes');因为有时我可能会更改顶部的文本,所以 div#notes 不再是 500。

  2. 还有如何仅在滚动动画完成时添加类,因为如果当动画滚动到达 div 时文本很长#notes 样式已经完成(我将 css transition 平滑地更改样式),我希望用户看到转换。

最佳答案

  1. 如何在不指定 500 .... 的情况下自动定位它。您只需要像这样获得 #notes 的顶部位置:$('#notes').position().top

  2. 还有如何仅在滚动动画完成时添加类... 您可能想查看 animate() API docs同样,animate() 有一个 complete: function(),一旦动画完成就会调用它。

这里是:

$('#goto-notes').click(function(){
var n = $('#notes);

$('#main').animate({
scrollTop: n.position().top
},{
duration: 2000,
complete: function(){
n.addClass('seen');
}
});
});

这里是 fiddle

关于javascript - 单击链接滚动到元素然后向元素添加一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20157894/

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