1

我有一个函数可以显示带有滚动数字的浮动气泡。它运行良好并在滚动时显示气泡,但主要是在滚动气泡后不断切换。这是下面的示例,请检查并帮助我代码哪里有问题。并提前感谢。

示例:http ://codepen.io/anon/pen/EPmKLJ

CSS:

body {
    position: relative;
    height: 800px;
    overflow: auto;
    width: 100%;
    background-color: pink;
}

#scrollbubble {
    display: none;
    position: fixed;
    top: 0;
    right: 10px;
    z-index: 98;
    padding: 8px;
    background-color: rgba(0, 0, 0, 0.2);
    color: #ffffff;
    border-radius: 3px;
}

#scrollbubble:after {
    content: "";
    position: absolute;
    top: 50%;
    right: -8px;
    height: 0;
    width: 0;
    margin-top: -4px;
    border: 4px solid transparent;
    border-left-color: rgba(0, 0, 0, 0.2);
}

JavaScript:

$.fn.scrollBubble = function() {
    var base = this,
        selector = $(base),
        win = $(window),
        $doc = $(document),
        container = $(base.selector),
        scrollTimer = null;

    if (win.width() > 940) {
        var viewportHeight = win.height(),
            scrollbarHeight = viewportHeight / $doc.height() * viewportHeight,
            progress = win.scrollTop() / ($doc.height() - viewportHeight),
            distance = progress * (viewportHeight - scrollbarHeight) + scrollbarHeight / 2 - container.height() / 2;

        container.css('top', distance).text(Math.round(progress * 100) + '%').fadeIn(100);

        if (scrollTimer !== null) {
            clearTimeout(scrollTimer);
        }
        scrollTimer = setTimeout(function() {
            container.fadeOut();
        }, 1000);
    }
};
$(window).scroll(function() {
    $('#scrollbubble').scrollBubble();
});

HTML:

<div id="scrollbubble"></div>
4

0 回答 0