简体   繁体   中英

How can I build a div that displays the .scrollTop value of the body?

On my webpage I've got the following div:

<div style="position:fixed; z-index:100;"></div>

I'm trying to write a script that will return the current .scrollTop value of the body within the above div (eg, if I'm scrolled 100px down the body, I would like the div to simply read: "100"), but I'm having a lot of trouble grasping .scrollTop and have no clue where to even start. Any help?

You'll need a timing loop to continuously display the value:

<div id="a">0</div>

JS:

var showScroll = setInterval(function() {
     document.getElementById('a').innerHTML = (document.body.scrollTop)                                 
},50)

I'm assuming you're using jQuery here. You can bind a listener to the scroll event and have it replace the content of your div with the result of scrollTop() , like this:

var div = $("div"); //Replace this selector with an ID for your div
$(document).scroll(function() {
    div.html($(window).scrollTop());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM