I'm making a horizontal scroller using jQuery. I have it working using the following
var wrapper = $('#wrapper'),
content = $('#scroll-content');
wrapper.bind('mousemove', function(e){
var wrapper_width = wrapper.width(),
content_width = content.width();
//wrapper and content width
var tmp = e.pageX * (content.outerWidth() - wrapper.outerWidth()) / wrapper.outerWidth();
//calculate new left margin
content.css({ 'margin-left': '-'+tmp+'px' });
开发者_如何学Python //set margin according
/*content.animate({
'margin-left': '-'+tmp+'px'
}, 30, 'easeOutSine');*/
});
Every mousemove event I calculate the new left margin, the slider spans 100% width of the screen.
This works, but I have two problems. It seems bad practise to be calling a calculation on every mousemove event as there are hundreds. Is there a better way, maybe using timers?
Another question, when the user first hovers the slider it jumps into place, I tried to use animate so that the slider would slide down to the correct position, but didn't seem to work. (commented at the bottom)
any help with these problems would be great. Thanks
You can use Ben Alman's Throttle Debounce plugin
And then do something like this:
$(document).ready(function() {
var wrapper = $('#wrapper'),
content = $('#scroll-content');
wrapper.bind('mouseenter mousemove', $.throttle(200, mousemove));
function mousemove(e) {
var wrapper_width = wrapper.outerWidth(),
content_width = content.outerWidth();
//calculate new left margin
var tmp = e.pageX * (content_width - wrapper_width) / wrapper_width;
content.stop().animate({
'margin-left': '-' + tmp + 'px'
}, 'fast', 'easeOutSine');
}
});
Example: http://jsfiddle.net/petersendidit/RkbP6/1/
I knew I had seen something similar in terms of throttling. John Resig posted a blog about problems with twitters infinite scroll. I used his solution in the following.
Here's the blog post for anyone interested.
http://ejohn.org/blog/learning-from-twitter/
$(document).ready(function() {
var wrapper = $('#wrapper'),
content = $('#scroll-content'),
did_move = false,
g_event;
wrapper.bind('mouseenter mousemove', function(e) {
did_move = true;
g_event = e;
});
setInterval(function() {
if (did_move) {
did_move = false;
//reset move bool
}
var wrapper_width = wrapper.outerWidth(),
content_width = content.outerWidth();
//update wrapper and content widths
var tmp = g_event.pageX * (content_width - wrapper_width) / wrapper_width;
//recalculate margin-left
content.stop().animate({
'margin-left': '-' + tmp + 'px'
}, 'fast', 'easeOutSine');
//animate into place.
}, 150);
});
精彩评论