简体   繁体   English

Div出现在页面加载中

[英]Div appears on page load

I have the following code which applies class which shows/hide a div. 我有以下代码适用于显示/隐藏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 CSS

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

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

Problem is when the page first loads the div is visible, then as soon as user scrolls it disappears, then reappears as it's supposed to. 问题是页面首次加载div时可见,然后用户滚动它便消失,然后按预期重新出现。 I want it to be opacity 0 until the offset distance is reached 我希望它是不透明度0,直到达到偏移距离

You could trigger the scroll callback function on page load with triggerHandler('scroll') . 您可以使用triggerHandler('scroll')在页面加载时触发滚动回调函数。 I would write it as follows: 我将其编写如下:

 $(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> 

Or, you could just call the function explicitly: 或者,您可以直接调用该函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM