jQuery - 如果 div 动态移动,如何将页面滚动到 div?
目前我正在创建一个网站,主要使用 PHP、SQL 和 JS 的混合。我使用 JS 使用 PHP 和 SQL 动态提取新数据。我当前遇到的问题是,我有一个按钮,单击该按钮将使页面根据偏移量每 2.5 秒滚动到当前 DIV。问题是元素移动后,该函数无法找到新的偏移量。
代码片段:
...
$(".button").click(function() {
$message_focus = "TRUE";
$to_focus=($(".focus_on_this").offset().top);
});
...
if ($message_focus = "TRUE") {
$("html, body" ).animate( { scrollTop: ($to_focus) },{ queue:false, duration:750 } );
}
...
这就是主要问题所在。一切正常,尽管它只到达初始 div 的起始位置。预先感谢您的回复。
Currently I am creating a website mainly using a mix of PHP, SQL, and JS. I use the JS to dynamically pull up new data using PHP and SQL. The current issue I am running into is that I have a button that when clicked will have the page scroll to the current DIV every 2.5 seconds based on offset. The issue is the function does not find the NEW offset once the element has moved.
Code snippets:
...
$(".button").click(function() {
$message_focus = "TRUE";
$to_focus=($(".focus_on_this").offset().top);
});
...
if ($message_focus = "TRUE") {
$("html, body" ).animate( { scrollTop: ($to_focus) },{ queue:false, duration:750 } );
}
...
That is where the main issue is. It all works fine, though it only goes to the initial div's starting location. Thank you in advance for your response.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每次滚动页面时,您都必须重新计算
.focus_on_this
的位置:You have to recalculate
.focus_on_this
's position everytime you scroll the page:div
如何动态移动?是否有任何事件导致它移动?如果是,那么我们需要在每次触发此事件时设置$to_focus=($(".focus_on_this").offset().top);
。仅在单击时设置它是行不通的。在您提到的按钮单击问题中,页面每 2.5 秒滚动到 div,但我没有看到任何此类代码。如果您想在一定时间后重复调用任何代码,则应该使用 setInterval,如下所示。
How does the
div
dynamically moves? Is there any event which causes it to move? If yes then we need to set$to_focus=($(".focus_on_this").offset().top);
every time this event is triggered. Only setting it on click will not work.In the question you have mentioned on button click the page scrolls to the div every 2.5 seconds but I dont see any such code. You should use setInterval if you want to call any code repititively after a certain period as below.