【问题标题】:jQuery - How to scroll the page to a div if div dynamically moves?jQuery - 如果 div 动态移动,如何将页面滚动到 div?
【发布时间】:2011-08-15 04:15:20
【问题描述】:

目前我正在创建一个主要使用 PHP、SQL 和 JS 组合的网站。我使用 JS 使用 PHP 和 SQL 动态提取新数据。我遇到的当前问题是我有一个按钮,单击该按钮时,页面会根据偏移量每 2.5 秒滚动到当前 DIV。问题是一旦元素移动,函数就找不到新的偏移量。

代码 sn-ps:

...

$(".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 的起始位置。提前感谢您的回复。

【问题讨论】:

  • 您尚未显示“将根据偏移量每 2.5 秒将页面滚动到当前 DIV”的代码。为此,您需要setInterval。你能显示你正在使用的代码吗?问题可能出在那个 sn-p...

标签: jquery scroll jquery-animate move offset


【解决方案1】:

每次滚动页面都必须重新计算.focus_on_this的位置:

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);

【讨论】:

    【解决方案2】:

    div 如何动态移动?是否有任何事件导致它移动?如果是,那么我们需要在每次触发此事件时设置$to_focus=($(".focus_on_this").offset().top);。只在点击时设置是行不通的。

    在您在按钮上提到的问题中,单击页面每 2.5 秒滚动到 div,但我没有看到任何此类代码。如果您想在一段时间后重复调用任何代码,则应使用 setInterval,如下所示。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 2018-01-07
      相关资源
      最近更新 更多