admin管理员组

文章数量:1289635

Using jquery, how can you set an event that triggers when there is a vertical scroll visible, and when you change from top half of page to bottom half of page, and vice versa.

So for example, if the vertical scroll bar is there, and then I am looking somewhere on the page which is in the top half of the page, and then move down so I am in the bottom half of the page, the function happens. Then if I move back up so I am in the top half again, the function happens.

Thanks.

Using jquery, how can you set an event that triggers when there is a vertical scroll visible, and when you change from top half of page to bottom half of page, and vice versa.

So for example, if the vertical scroll bar is there, and then I am looking somewhere on the page which is in the top half of the page, and then move down so I am in the bottom half of the page, the function happens. Then if I move back up so I am in the top half again, the function happens.

Thanks.

Share Improve this question asked Aug 2, 2013 at 18:37 omegaomega 43.9k90 gold badges285 silver badges521 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4
var midHeight = jQuery(window).height() / 2 //Splits screen in half
$(window).scroll(function () {
    if ($(window).scrollTop() > midHeight) {
        //Do something on bottom
    } else {
        //Do something on top
    }
})

well jQuery does have these methods you can use on an element:

.scrollTop() - get top scroll position on an element in the viewport

.scrollLeft() - get left scroll position on an element in the viewport

Also there is the scroll event - that triggers when a viewport/element scrolls within another one (or the window):

.scroll()

$(window).scroll(function () { 
  if ($(window).scrollTop() > $('body').height() / 2) {
      //code goes here...
  } 
});

Detect Scroll

var s = $('body').scrollTop();

jQuery scrollTop()

Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.

You may be interested to know:

$().scrollTop()//how much has been scrolled
$().innerHeight()// inner height of the element
DOMElement.scrollHeight//height of the content of the element

JSFIDDLE DEMO

本文标签: javascriptHow to detect vertical scroll position using jqueryStack Overflow