我对你的代码有点乱,我想问题是
position.left
返回对象相对于窗口的位置,并返回滚动条位置。所以只要改变位置变量
#scrollbar
到
#grabber
为我工作。
var position = $("#grabber").position();
因此,您不需要保存
grabberStart
位置
最后,由于某种原因,我花了一段时间才弄明白
window
事件。所以我把它们换成
document
巴姆!我工作得很好。
这是用我提到的更改更新的脚本。顺便说一下,这个网站看起来不错!
// **********************************************
// Throll: Toms Horizontal Scroll
// Developer: Tom Elders
// Contact: him@tomelders.com
// **********************************************
// File: throll.1.0.js
// Description:
// CSS and JS horizontal scriolling that doesn't
// break the browers native functionality.
//
// Copyright 2010, Tom Elders
//
// **********************************************
var grabberClicked = false;
var dragStart;
var ratio;
var scrollBound;
var totalWidth = 0;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
$(document).ready(function(){
$("#projects").width(getTotalWidth());
setup();
$("#grabber").mousedown(startScroll);
$(document).mouseup(endScroll);
$("#viewport").scroll(positionGrabber);
$(window).resize(setup);
});
function getTotalWidth(){
$(".project").each(function(){
totalWidth += $(this).width();
totalWidth += parseInt($(this).css("marginLeft")) * 2;
})
return totalWidth;
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function setup(){
ratio = $("#viewport").width() / $("#projects").width();
// grabber width
$("#grabber").width( $("#scrollbar").width() * ratio );
scrollBound = $("#scrollbar").width() - $("#grabber").width();
// incase the user resizes the window, position the grabber accordingly
positionGrabber();
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function startScroll(event){
$(document).bind('mousemove', scroll);
var position = $("#grabber").position();
dragStart = event.pageX - position.left;
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function endScroll(event){
$(document).unbind('mousemove', scroll);
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function scroll(event){
var newPos = event.pageX - dragStart;
// bounds
newPos = (newPos > 0) ? newPos : 0;
newPos = (newPos < scrollBound) ? newPos : scrollBound;
viewportPos = ( $("#projects").width() * ( newPos / $("#scrollbar").width() ) );
$("#viewport").scrollLeft(viewportPos);
$("#grabber").css("left", newPos);
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function positionGrabber(event){
var grabberPos = $("#scrollbar").width() * ($("#viewport").scrollLeft() / $("#projects").width());
$("#grabber").css("left", grabberPos);
}