如何通过window滚动事件实现div元素居中?
Hey Billy, let's get that div centered as you scroll the window—you're already halfway there with the code you've started! Let's fix up your existing code and walk through the solution step by step.
First, I noticed a small typo in your jQuery: you're targeting #ifOne, but your HTML has a div with id div1. I'll adjust the code below to match your actual HTML structure.
Step 1: Basic HTML & CSS Setup
First, make sure your div has a non-static position (so we can adjust its top property). Here's your base code with some basic styling to see the div clearly:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style> #div1 { width: 200px; background: #eaeaea; padding: 20px; position: absolute; /* Use fixed if you want it stuck to the viewport even when scrolling */ } </style> <div id="div1">Some Content</div>
Step 2: Updated jQuery Code
The key to centering the div as you scroll is calculating the correct top position based on the window's height, scroll position, and the div's own height. Here's the full working code:
$(window).scroll(function() { // Get essential values var windowHeight = $(window).height(); var scrollTop = $(window).scrollTop(); var divHeight = $("#div1").innerHeight(); // Includes padding; use .height() for content-only height // Calculate the top position to center the div vertically in the viewport var targetTop = scrollTop + (windowHeight - divHeight) / 2; // Apply the position to the div $("#div1").css("top", targetTop + "px"); }); // Trigger scroll on page load to set initial centered position $(window).trigger("scroll");
How It Works
Let's break down the logic:
scrollTopgives us how far the user has scrolled from the top of the page.(windowHeight - divHeight) / 2calculates the equal space needed above and below the div to center it vertically in the window.- Adding those two values gives us the exact
topposition the div needs to stay centered as the user scrolls.
Bonus: Horizontal Centering
If you also want the div centered horizontally, add this snippet inside the scroll function:
var windowWidth = $(window).width(); var divWidth = $("#div1").innerWidth(); var targetLeft = (windowWidth - divWidth) / 2; $("#div1").css("left", targetLeft + "px");
Quick Note on CSS Alternatives
If you don't strictly need to use a scroll event, you can achieve fixed viewport centering with pure CSS (no JavaScript needed):
#div1 { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
But since you specifically asked to use the window scroll event, the jQuery method above is perfect for your needs.
内容的提问来源于stack exchange,提问作者Billy

