Jquery Scrolling div - Prevent from entering site

2019-02-18 23:34发布

问题:

I have a side menu on my site that i would like always visible.
To accomplish this, I am using the following code sample from this page:

http://camwebdesign.com/demos/jquery-scrolling-element.html

The problem is that unlike the sample my site has a huge 1000px height footer. When the user scrolls the content over the footer div, the side menu overlaps it. Is there a way to modify the Jquery code where it has a boundry of 1000px on the bottom to prevent this?

Thanks!

<html> 

<title>Keep element in view while scrolling using JQuery</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js?ver=CDN"></script> 
<script> 
    $().ready(function() {
        var $scrollingDiv = $("#scrollingDiv");

        $(window).scroll(function(){            
            $scrollingDiv
                .stop()
                .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );          
        });
    });
</script> 
<div style="float: left; width: 70%"> 

<h1>Keep element in view while scrolling using JQuery</h1> 

<div id="scrollingDiv" style="position: absolute;   top: 32px; right: 16px; width: 21%; padding: 0% 2% 2% 2%; border: 2px solid red; background-color: #ffeaea;"> 
    <h2>Scrolling Element</h2> 
    Scroll down/up to see me smoothly reposition myself and keep in view.<br /><br /> 

    <em>Smooooooooooooooooooth</em><br /> 

</div> 


 <div style="clear:both;"></div>

 <div id="footer" style="width:100%; height:1000px; background:#333; color:#FFF;" >
 <h1>Footer</h1>





 </div>

回答1:

Demo

http://jsfiddle.net/NsfwM/

fullscreen http://jsfiddle.net/NsfwM/embedded/result/

JS

var $scrollingDiv = $("#scrollingDiv");

$(window).scroll(function(){            
    var y = $(this).scrollTop(),
        maxY = $('#footer').offset().top,
        scrollHeight = $scrollingDiv.height();

    if(y< maxY-scrollHeight ){
        $scrollingDiv
        .stop()
        .animate({"marginTop": ($(window).scrollTop()) + "px"}, "slow" );        
    }    
});

And another with your 30px offset in place http://jsfiddle.net/NsfwM/1/