Div出现在页面加载上

时间:2017-10-31 07:19:20

标签: javascript jquery html css

我有以下代码,它应用显示/隐藏div的类。

$(document).ready(function($) { 
      function reusuableUpAnimFunc(elementName, offset, hideClass, showClass) {
        $(window).scroll(function() {
        $animation = $(elementName);                
          ($(this).scrollTop() > offset) ? $animation.removeClass(hideClass).addClass(showClass):
            $animation.addClass(hideClass).removeClass(showClass);
        });
      } 

reusuableUpAnimFunc('#top-btn', 400, 'element-hide', 'element-show');
});

CSS

.element-hide {
 opacity: 0;
 visibility: hidden;
}

.element-show {
 opacity: 1;
 visibility: visible;
}

问题是当页面首次加载时div是可见的,然后一旦用户滚动它就会消失,然后重新出现,因为它应该。我希望它是不透明度0,直到达到偏移距离

1 个答案:

答案 0 :(得分:1)

您可以使用triggerHandler('scroll')在页面加载时触发滚动回调函数。我会写如下:



$(document).ready(function($) {
    function swapClass(selector, class1, class2, setClass2) {
        $(selector).toggleClass(class1, !setClass2).toggleClass(class2, setClass2);
    }

    function reusuableUpAnimFunc(selector, offset, hideClass, showClass) {
        $(window).scroll(function () {
            swapClass(selector, hideClass, showClass, $(this).scrollTop() > offset);
        }).triggerHandler('scroll');
    }

    reusuableUpAnimFunc('#top-btn', 50, 'element-hide', 'element-show');
});

.element-hide {
    opacity: 0;
    visibility: hidden;
}

.element-show {
    opacity: 1;
    visibility: visible;
}
p { height: 50px };

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>scroll down...<p>
<div id="top-btn">This will appear on scrolling</div>
<p></p><p></p><p></p><p></p><p></p>
&#13;
&#13;
&#13;

或者,您可以明确地调用该函数:

    // ...
    $(window).scroll(function () {
        swapClass(selector, hideClass, showClass, $(this).scrollTop() > offset);
    });
    // Call it now:
    swapClass(selector, hideClass, showClass, $(this).scrollTop() > offset);
    // ...