[英]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. 我修改了这段代码以创建一个大div,该div在较小的div内水平滚动,具体取决于鼠标的位置。
You can see my example here.. http://thetally.efinancialnews.com/tallyassets/20years/index.html 您可以在这里看到我的示例。.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. 我要达到的目的是使内部(黄色)div停在最大的左:0px处,换句话说,如果您走的那么远,黄色div的最左端将卡在外部div的最左端。
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. 我尝试使用“ if else”语句来实现这一点,但是由于这段代码每30秒运行一次,因此会产生奇怪的结果,而我找不到解决方案。 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 未来的额外注意事项:parseInt默认使用10为底:),因此parseInt(“ 20px”)等于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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.