Show Div when scroll position

一曲冷凌霜 提交于 2019-12-17 04:46:25

问题


First of all i would like to refer to this website: http://annasafroncik.it/ I love the way the animations come into view. Is it hard to create a similar function in jquery? Are there any plugins to create such an effect?

Hope someone will help me out.


回答1:


Basically, you want to add a "hideme" class to every element you want hidden (then you set that class to "opacity:0";

Then, using jQuery you set a $(window).scroll() event to check the location of the bottom of every "hideme" element against the bottom edge of your visible window.

Here's the meat of it ...

/* 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);

        }

    }); 

});

Here's a full jsfiddle: http://jsfiddle.net/tcloninger/e5qaD/




回答2:


Plugins? Maybe, but you could definitely build any animation combinations you could imagine with jQuery by yourself. If you have a firm grasp on selectors and CSS, the sky's the limit! I'd suggest starting on the jQuery website and checking out some examples.

To help get the ball rolling, and maybe give you some ideas if you're already familiar with jQuery, you could try the following...figure out how far down the page your div is, listen for scroll events, and when the div comes into focus (i.e.: the page has been scrolled past the div's position you worked out), run an animation. Something like:

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

I hope I haven't messed up my syntax!




回答3:


Try this . It worked for me

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

and the css for this is

.showmydiv{display:block}


来源:https://stackoverflow.com/questions/9097501/show-div-when-scroll-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!