admin管理员组

文章数量:1279213

I have a 'back button' that I would like to stick to the header until you scroll past a certain point (so I have it absolutely positioned but would like it positioned 'fixed' when you scroll past the header).

Kinda like the 'GAMEHQ' section does here:

Any suggestions? Thanks!

I have a 'back button' that I would like to stick to the header until you scroll past a certain point (so I have it absolutely positioned but would like it positioned 'fixed' when you scroll past the header).

Kinda like the 'GAMEHQ' section does here: http://scores.espn.go./mlb/preview?gameId=311027124

Any suggestions? Thanks!

Share Improve this question asked Oct 27, 2011 at 22:02 stewart715stewart715 5,63711 gold badges49 silver badges81 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

The function which gives you information about where you are in the page is scrollTop(). With it you can detect if you're past a certain point, and then modify the CSS of an item to make it position: fixed, for example.

Here's an example:

$(document).ready(function() {
    $(window).scroll(function() {
        if ($(window).scrollTop() >= 120) {
            $('#topThing').css('position', 'fixed');
        } else {
            $('#topThing').css('position', 'relative');
        }
    });
});

And here's a JSFiddle showing how it works.

This example uses jQuery but could be altered fairly easily. This function should be close to what you want. The 100 is the number of pixels down the page you'd want to change the class of your #nav. In your CSS you'd then want to make sure you had a #nav.scrolling declaration to handle the change to position: fixed.

$(window).scroll(function(){
  if ($(this).scrollTop() > 100) {
    $("#nav").addClass("scrolling");
  }
});

本文标签: javascriptjquery detect coordinate of top of page after scrollingStack Overflow