【问题标题】:jquery window scroll function to an id then do somethingjquery窗口滚动功能到一个id然后做一些事情
【发布时间】:2013-09-24 06:56:50
【问题描述】:

我只是想知道在使用窗口滚动功能到某个 id 而不是以像素为单位的高度时是否可以触发警报。我问的原因是我意识到高度会根据显示位置而有所不同,因此引用 id 可能更有效。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    使用 .position() .offset() 可以获取元素的位置。 将它与您的滚动功能结合起来,您将拥有一个“到 id 的窗口滚动功能”。

    // store the position of the element in position
    var position = $('#idOfElement').offset(); //=position() but always relative to 
                                               //document instead of parent. 
                                               //thanks to sidonaldson
    
    // on scrolling of the document do something
    $(document).scroll(function () {
        //the current height
        var y = $(this).scrollTop();
    
        //If the current Y is bigger than the element. (you scrolled beyond the element)
        if(y >= position.top){
            //do something
        }else{
            //do something else 
        }
    });
    

    【讨论】:

    • 谢谢,这正是我一直在寻找的 :)
    • 使用偏移而不是位置。请下次更好地表达您的问题,以免人们浪费时间回答!
    【解决方案2】:

    使用 jQuery,您可以将页面动画化为 id。

    $("html, body").animate({ scrollTop: $('#your-id').offset().top }, 1000, function(){
        alert("Scroll end");
    });
    

    首先你必须使用 'html,body' 让它跨浏览器。

    然后你通过计算它相对于页面顶部的偏移量来计算 id 元素的位置(而不是相对于父元素的位置)

    然后你以毫秒为单位设置你的速度。

    最后你传入一个函数引用,或者,在这种情况下,定义一个回调函数 - 在这里你可以添加你的警报。

    请注意,这必须在 document.ready 被触发之后。

    【讨论】:

    • 据我所知,您不需要使用html,body。只需body,它就适用于我测试过的所有浏览器。 (IE9、Chrome、Opera 12、Firefox...)哪些没有?
    • stackoverflow.com/questions/12222485/…这个问题告诉你为什么:)
    • 并非如此。他没有指定浏览器,也没有给出任何数据的链接来证明这一点。他可能指的是非常旧的浏览器......
    • Alvaro - 这是跨浏览器滚动页面的公认方式。 Safari 在以前的版本中存在问题,并且浏览器处理“设置”和“获取”滚动顶部的方式存在差异。 stackoverflow.com/questions/5371139/… 我无法具体说明原因,因为长期以来这一直是公认的做法。为了
    • 是的,解决起来很简单,我只是有点好奇,因为到目前为止我在任何浏览器中都没有发现任何问题。还是谢谢!
    【解决方案3】:

    试试这个:

    //getting the Y position of the element you want to scroll to
    var position = $('#element').offset().top;
    
    //scrolling to the element with an animation of 700 miliseconds
    $('body').animate({
        scrollTop: position
    }, 700, function(){  //callback function (executed when animation finishes)
        alert("Hello there!");
    });
    

    现场演示:http://jsfiddle.net/wdFCm/2/

    【讨论】:

    • 他不想滚动到某个el.top;但想在他到达el.top 时触发一些东西。至少这是我对他的问题的看法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    相关资源
    最近更新 更多