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

求助:实现Input聚焦时页面滚动至指定Div的JavaScript方案

Solution to Auto-Scroll on Input Focus

Here's a straightforward implementation that achieves exactly what you're asking for. When the search input gains focus, the page will smoothly scroll to position the search box at the top of the viewport—ensuring the red (overtop) and yellow (top) boxes are completely out of sight.

Full Code Example

<!DOCTYPE html>
<html>
<head>
  <style>
    #overtop { width: 500px; height: 100px; background: red; }
    #top { width: 500px; height: 100px; background: yellow; }
    #searchbox { margin: 10px 0; }
    #content { width: 500px; height: 200px; background: blue; }
  </style>
</head>
<body>
  <div id="overtop"></div>
  <div id="top"></div>
  <div id="searchbox">
    <input type="text" id="myInput" placeholder="enter.." title="search">
  </div>
  <div id="content"></div>

  <script>
    // Wait for the DOM to fully load before attaching events
    document.addEventListener('DOMContentLoaded', function() {
      // Get the search input element
      const searchInput = document.getElementById('myInput');
      
      // Add focus event listener
      searchInput.addEventListener('focus', function() {
        // Get the searchbox container
        const searchBox = document.getElementById('searchbox');
        
        // Smooth scroll to align searchbox at the top of the viewport
        searchBox.scrollIntoView({ 
          behavior: 'smooth', // Use 'auto' for instant scroll
          block: 'start' // Align the top of the element with the viewport top
        });
      });
    });
  </script>
</body>
</html>

How It Works:

  • DOMContentLoaded: Ensures our JavaScript runs only after all HTML elements are loaded, so we don't try to access elements that don't exist yet.
  • Focus Event Listener: Triggers the scroll action when the input is clicked or tabbed into.
  • scrollIntoView(): A built-in browser method that smoothly scrolls the target element into view. The block: 'start' option aligns the top of the searchbox with the top of the viewport, pushing the red and yellow boxes out of sight.

Alternative: Instant Scroll

If you prefer an immediate jump instead of smooth scrolling, replace the scrollIntoView line with:

window.scrollTo({ top: searchBox.offsetTop, left: 0, behavior: 'auto' });

Or even simpler:

window.scrollTo(0, searchBox.offsetTop);

This solution is lightweight, uses native browser APIs (no external libraries needed), and works across all modern browsers.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:59:17