Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检测页面是否在文档加载时滚动_Javascript_Jquery - Fatal编程技术网

Javascript 检测页面是否在文档加载时滚动

Javascript 检测页面是否在文档加载时滚动,javascript,jquery,Javascript,Jquery,我正在使用scrollTop检测用户是否滚动,然后fadeIn一个元素: $(document).ready(function() { // scroll to top $(window).scroll(function() { if ($(this).scrollTop() >= 700) { // if page is scrolled more than 700px $('#return-to-top').fadeIn(200)

我正在使用
scrollTop
检测用户是否滚动,然后
fadeIn
一个元素:

$(document).ready(function() {
    // scroll to top
    $(window).scroll(function() {
        if ($(this).scrollTop() >= 700) { // if page is scrolled more than 700px
            $('#return-to-top').fadeIn(200);
        } else {
            $('#return-to-top').fadeOut(200);
        }
    });
});
如果用户加载页面然后滚动,则效果良好,但如果用户已经低于700px并重新加载或返回到同一页面,则元素在加载文档时不会自动
fadeIn
。似乎没有检测到页面已经滚动


知道我的代码有什么问题吗?

只要在文档准备好后进行测试就可以了

最好创建一个函数

function checkScroll(){
    if ($(window).scrollTop() >= 700) {
        $('#return-to-top').fadeIn(200);
    } else {
        $('#return-to-top').fadeOut(200);
    }
}

$(document).ready(function() {
    checkScroll();
    $(window).scroll(checkScroll);
});

以这种方式调用函数

准备好文档末尾的这一行

$(window).scroll();

只需在委托后触发滚动

$(document).ready(function() {
    // scroll to top
    $(window).scroll(function() {
        if ($(this).scrollTop() >= 700) { // if page is scrolled more than 700px
            $('#return-to-top').fadeIn(200);
        } else {
            $('#return-to-top').fadeOut(200);
        }
    }).scroll();
    //^^^^^^ trigger scroll.
});

你能发布
HTML