【问题标题】:Show Div when scroll position滚动位置时显示 Div
【发布时间】:2012-02-24 05:34:23
【问题描述】:

首先我想参考这个网站:http://annasafroncik.it/ 我喜欢动画进入视野的方式。 在jquery中创建类似的功能很难吗? 有没有插件可以制作这样的效果?

希望有人能帮助我。

【问题讨论】:

    标签: jquery scroll jquery-animate


    【解决方案1】:

    基本上,您想为每个要隐藏的元素添加一个“hideme”类(然后将该类设置为“opacity:0”;

    然后,使用 jQuery 设置 $(window).scroll() 事件来检查每个“hideme”元素底部与可见窗口底部边缘的位置。

    这就是它的核心......

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){
    
        /* Check the location of each desired element */
        $('.hideme').each( function(i){
    
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
    
            /* If the object is completely visible in the window, fade it in */
            if( bottom_of_window > bottom_of_object ){
    
                $(this).animate({'opacity':'1'},500);
    
            }
    
        }); 
    
    });
    

    这是一个完整的 jsfiddle:http://jsfiddle.net/tcloninger/e5qaD/

    【讨论】:

    • 哇我喜欢这个例子,非常清晰和干净的代码!问题解决了
    • 你提到了一个插件,所以这是我刚刚整理的一个:timothyaaron.com/js/fadein.on.scroll.js 它会自动隐藏当前视图之外的 所有 元素,并在滚动时将它们淡入(使用“hideme”类元素,所以请确保您没有出于任何其他原因使用它)。
    • 我更新了你的 jsfiddle (jsfiddle.net/e5qaD/1151) 以加快大页面的速度。更新会在所有内容都显示后关闭滚动侦听器,并且仅在需要时淡入项目。
    • 我在这里根本不是专家,但我觉得现在你应该使用.offset() 而不是.position()。另外,顺便说一句,使用 opacity 而不是 jQuery 的 hide()toggle() 等很重要,因为后面实际会弄乱元素的位置。
    • The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. 所以,是的,如果您的偏移父级不是文档,您必须使用.offset()。我将调整代码以反映这一点。
    【解决方案2】:

    插件?也许吧,但你绝对可以自己用 jQuery 构建任何你能想象到的动画组合。如果您对选择器和 CSS 有一定的把握,那就没有限制!我建议从jQuery website 开始,然后查看some examples

    如果你已经熟悉 jQuery,为了帮助你顺利进行,也许会给你一些想法,你可以试试下面的方法......找出你的 div 在页面的下方有多远,监听滚动事件,并且当div 成为焦点时(即:页面已滚动到您计算出的div 的位置),运行动画。比如:

    <div id="my_div">Some content</div>
    
    <script type="text/javascript">
    
        $(document).ready(function() {
    
            var my_div = $("#my_div");
            var div_top = my_div.offset().top;
    
            $(document).scroll(function() {
                if (div_top <= $(document).scrollTop()) {
                    // do some cool animations...
                }
            });
    
        });
    
    </script>
    

    希望我的语法没有搞砸!

    【讨论】:

      【解决方案3】:

      试试这个。它对我有用

      $(document).scroll(function() {
        var y = $(this).scrollTop();
        if (y > 400) {
          $("body").addClass("allowshow");
        } else {
          $("body").removeClass("allowshow");
        }
      });
      

      这个的css是

      .showmydiv{display:block}
      

      【讨论】:

        猜你喜欢
        • 2011-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-04
        • 2014-03-19
        • 2015-06-11
        • 2014-05-26
        • 1970-01-01
        相关资源
        最近更新 更多