简体   繁体   English

jQuery - 如果 div 动态移动,如何将页面滚动到 div?

[英]jQuery - How to scroll the page to a div if div dynamically moves?

Currently I am creating a website mainly using a mix of PHP, SQL, and JS.目前我正在创建一个网站,主要使用 PHP、SQL 和 JS 的组合。 I use the JS to dynamically pull up new data using PHP and SQL.我使用 JS 使用 PHP 和 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.我遇到的当前问题是我有一个按钮,单击该按钮时,页面会根据偏移量每 2.5 秒滚动到当前 DIV。 The issue is the function does not find the NEW offset once the element has moved.问题是元素移动后 function 找不到新的偏移量。

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.一切正常,尽管它只到达初始 div 的起始位置。 Thank you in advance for your response.预先感谢您的回复。

How does the div dynamically moves? div如何动态移动? Is there any event which causes it to move?是否有任何事件导致它移动? If yes then we need to set $to_focus=($(".focus_on_this").offset().top);如果是,那么我们需要设置$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.在您在按钮上提到的问题中,单击页面每 2.5 秒滚动到 div,但我没有看到任何此类代码。 You should use setInterval if you want to call any code repititively after a certain period as below.如果您想在一段时间后重复调用任何代码,您应该使用 setInterval,如下所示。

setInterval(function(){
   //Do something after every 2000 milliseconds

}, 2000);

You have to recalculate .focus_on_this 's position everytime you scroll the page:每次滚动页面时,您都必须重新计算.focus_on_this的 position:

var $message_focus = false;

$(".button").click(function() {
    $message_focus = true;
});

setInterval(function() {
    if ($message_focus == true) {
        $("html, body" ).animate({
            scrollTop: $(".focus_on_this").offset().top
        },{
            queue:false,
            duration:750
        });
    }
}, 2500);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM