根据scrollTop更改图像的位置

时间:2015-02-10 22:45:41

标签: javascript jquery scroll scrolltop

当用户滚动到280以上时,我会弹出一个回到顶部的图像。问题是当您到达底部时图像位于页脚中的链接上。因此,一旦用户距离页面底部大约90px,我想改变图像的位置 - 我想要“底部”:'35px'为95.页面高度总是在变化fyi。我的代码:

function update() {
    if ($(window).scrollTop() > 280) {
        $('#btt').animate({
            "bottom": '35px'
            }, 300);
    }

    else {
        $('#btt').animate({
            "bottom": '-80px'
        }, 300);
        }
    }
setInterval(update, 500);

1 个答案:

答案 0 :(得分:0)

最好只在滚动页面时检查滚动位置,而不是每隔1/2秒检查一次。

我在这里整理了一个我认为你想要的工作演示: http://jsfiddle.net/swpqpv4r/5/

基本上我们需要查看窗口 bottom 的滚动位置,因为我们使用document.body.scrollTop + $(win).height()滚动而不是顶部。 Normaly我们可能想担心如果要调整窗口大小会发生什么,但我们每次都在滚动事件内部计算这个,所以如果窗口改变大小,它应该不是问题。

接下来,我们需要知道页脚顶部何时滚动到窗口底部之上。我们可以使用$("#footer").position().top;来查看它的最高位置。

希望代码的注释足以帮助解释它。如果您有任何问题,请告诉我。

<强> HTML

<header>Top</header>
<br><br><br> <!-- Lots of these for testing -->
<footer id="footer">Bottom</footer>
<a id="btt" href="javascript:{};">Back to top</a>

<强>的JavaScript

$(function(){
    //select once and re-use later
    var $win = $(window);
    var $btt = $("#btt");
    var $foot = $("#footer");
    var bttDisplay = 500;
    var footerHeight = $foot.outerHeight();
    var footerTop = $foot.position().top;

    function updateScroll() {
        var scrollBottom = document.body.scrollTop + $win.height();

        if (scrollBottom >= bttDisplay && scrollBottom <= footerTop) {
            //show it by setting the bottom position to 0
            animateBtt(0);
        }else if (scrollBottom >= footerTop) {
            //move it up above the footer's top position
            animateBtt(footerHeight);
        }else {
            //hide it by setting the bottom position to the negative value of it's height
            animateBtt($btt.height() * -1);
        }
    }

    function animateBtt(pos){
        $btt.animate({
            "bottom": pos
        }, 300);
    }

    //run initially
    updateScroll();

    //Create a var to hold the timer
    var scrollTimer = null;
    $win.on("scroll",function(ev){
        //when scrolling, clear the timer
        clearTimeout(scrollTimer);
        //Now set the timer to run a function after a small delay.
        //This prevents the update from happening too many times when you scroll
        scrollTimer = setTimeout(updateScroll, 50);
    });

    //click to scroll back up
    $btt.on("click",function(){
        $('html, body').animate({scrollTop:0},300);
    })

});

<强> CSS

html,body{
    margin:0;
    padding:0;
}
header, footer{
    background: #CCC;
    padding: 10px;
}
#btt{
    position:fixed;
    height: 30px;
    width: 100px;
    text-align:center;
    bottom: -30px;
    right:0;
    background: #F00;
    color: #FFF;
    z-index: 1000;
}
相关问题