简体   繁体   中英

Stop div scrolling past set position

I adapted this code to create a large div which scrolls horizontally inside a smaller div, depending on the position of the mouse.

You can see my example here.. http://thetally.efinancialnews.com/tallyassets/20years/index.html

What I am trying to achieve is for the inner (yellow) div to stop at a maximum of left:0px, in other words the far left of the yellow div will become stuck to the far left of the outer div if you go that far.

I tried to implement this with an 'if else' statement, however as this piece of code gets run every 30th of a second it creates a strange result, which I can't find a solution for. I'm sure its very simple but its stumped me

You can see my code here...

var x=0, 
rate=0,
maxspeed=10;
var backdrop = $('.container');
var years = $('.events');

$('.direction', backdrop).mousemove(function(e){
    var $this = $(this);
    var left = $this.is('.left');
    if (left){
        var w = $this.width();
        rate = (w - e.pageX - $(this).offset().left + 1)/w;
    } else {
        var w = $this.width();
        rate = -(e.pageX - $(this).offset().left + 1)/w;
    }
});

backdrop.hover(function(){
    var scroller = setInterval( moveBackdrop, 30 );
    $(this).data('scroller', scroller);
},
function(){
    var scroller = $(this).data('scroller');
    clearInterval( scroller );
});   

function moveBackdrop(){
    if ( parseInt(years.css("left"), 10) <= 0 ) {
        x += maxspeed * rate;
        var newpos = x+'px';
        years.css('left',newpos);
    } else {
        years.css('left','0');
    }
}

The code in question is right here at the end^

Is this what you were trying to do?

function moveBackdrop(){
    if ( parseInt(years.css("left"), 10) <= 0 && rate < 0 ) {
        // Means that the element is already at left: 0 or less,
        // and we are trying to move it even more left with rate being negative.
        // So keep the element at left: 0
        years.css('left','0');
    } else {
        x += maxspeed * rate;
        var newpos = x+'px';
        years.css('left',newpos);
    }
}

Extra note for future: parseInt uses base 10 by default :) so parseInt("20px") will equal 20

Final Edit: Ah there is an even better way to do it.

function moveBackdrop(){
    x += maxspeed * rate;
    if( x < 0 ) x = 0; // If left less than 0, fix it at 0
    var newpos = x+'px';
    years.css('left',newpos);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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