You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将无用户操作时页面跳转至顶部改为平滑滚动?技术方案咨询

Smooth Scroll to Top on User Idle (Instead of Hard Redirect)

Hey there! Let's adjust your existing idle timer script to trigger a smooth scroll to the top instead of that abrupt redirect. Here's the modified code along with breakdowns of the key changes:

Modified Working Code

<script>
(function() {
  const idleDurationSecs = 60; // Idle timeout length in seconds
  let idleTimeout; // Variable to hold the timeout, don't modify directly

  const resetIdleTimeout = function() {
    // Clear any existing timeout if it's active
    if(idleTimeout) clearTimeout(idleTimeout);
    // Set new timeout to trigger smooth scroll after idle period
    idleTimeout = setTimeout(() => {
      // Replace hard redirect with smooth scroll animation to top
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
      // Alternative option (works just as well):
      // document.documentElement.scrollIntoView({ behavior: 'smooth' });
    }, idleDurationSecs * 1000);
  };

  // Initialize the idle timer when the page loads
  resetIdleTimeout();

  // Reset the timer whenever the user interacts with the page
  ['click', 'touchstart', 'mousemove'].forEach(evt => 
    document.addEventListener(evt, resetIdleTimeout, false)
  );
})();
</script>

Key Changes Explained

  • Removed the redirectUrl variable: Since we're no longer redirecting to a URL, this variable is unnecessary now and can be cleaned up.
  • Replaced location.href with smooth scroll logic: Instead of forcing a jarring URL jump, we use window.scrollTo() with the behavior: 'smooth' parameter. This tells the browser to animate the scroll to the page top gently.
    • If you prefer, document.documentElement.scrollIntoView({ behavior: 'smooth' }) is another valid way to achieve the same smooth scroll effect.

Quick Compatibility Note

The behavior: 'smooth' option works in all modern browsers (Chrome, Firefox, Edge, Safari 15.4+). If you need to support older browsers (like Safari versions before 15.4), you can add a simple fallback: check if smooth behavior is supported, and use instant scroll window.scrollTo(0, 0) for unsupported cases.

内容的提问来源于stack exchange,提问作者kamal_hamad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 22:17:48