简体   繁体   中英

jQuery ScrollTop() function not working

I'm trying to implement the scrollTop() function with a responsive design, but for some reason this code won't work.

The following checks if the page is completely loaded, than it it checks if the page has been scrolled at all. Than, after making sure that the page has scrolled past the header, it makes an image appear that is fixed at the top of the screen which will send the page to the top of the screen. My problem is that the image won't appear. Any help is appreciated!

$(document).ready(function() {
            if ($(document).width() > 650) {
                $('#welcome').css('padding-top', $('#header').height() + 50 + 'px');
                $(document).scroll(function() {
                    if ($(document).scrollTop() >= $('#header').height()) {
                        $('#up-arrow').css('position', 'fixed').css('right', '0');
                    } else {
                        $('#up-arrow').css('display', 'none');
                    }
                });
            } else {
                $('#welcome').css('padding-top', '25px');
            }
        });
        $(window).resize(function() {
            if ($(document).width() > 650) {
                $('#welcome').css('padding-top', $('#header').height() + 50 + 'px');
                $(document).scroll(function() {
                    if ($(document).scrollTop() >= $('#header').height()) {
                        $('#up-arrow').css('position', 'fixed').css('right', '0').css('display','block');
                    } else {
                        $('#up-arrow').css('display', 'none');
                    }
                });
            } else {
                $('#welcome').css('padding-top', '25px');
            }
        });

It took some troubleshooting, but I believe I found the issue:

If the document is not scrolled past the header on load, you set the css for the up-arrow to display:none .

But, when it IS scrolled far enough, you only set the position: fixed - you don't actually turn it back on.

So change this line:

$('#up-arrow').css('position', 'fixed').css('right', '0');

To:

$('#up-arrow').css({'position': 'fixed', 'display': 'block', 'right' : 0});

And it will work.

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