在JQ上定义滚动条插件

$.fn.definedScroll = function(direction, childId, scrollId) {
var parent = $(this),
child = parent.find(childId),
scroll = parent.find(scrollId);

var childDiffHeight = child.height() - parent.height(),
scrollDiffHeight = parent.height() - scroll.height(),
childDiffWidth = child.width() - parent.width(),
scrollDiffWidth = parent.width() - scroll.width();

if (direction === "y") {
if (childDiffHeight < 0 || scrollDiffHeight < 0) {
return false
}
}
if (direction === "x") {
if (childDiffWidth < 0 || scrollDiffWidth < 0) {
return false
}
}
scroll.on("mousedown", function(ev) {
ev.preventDefault();
var initTop = ev.clientY,
initLeft = ev.clientX,
top = parseInt(scroll.css("top")),
left = parseInt(scroll.css("left"));

$(document).bind("mousemove",
function(ev) {
if (direction === "y") {
var diffT = ev.clientY - initTop + top,
scrollDiffPercent = diffT / scrollDiffHeight,
childMoveT = -scrollDiffPercent * childDiffHeight;
if (diffT < 0) {
scroll.css("top", 0);
child.css("margin-top", 0)
} else if (diffT > scrollDiffHeight) {
scroll.css("top", scrollDiffHeight);
child.css("margin-top", -childDiffHeight)
} else {
scroll.css("top", diffT);
child.css("margin-top", childMoveT)
}
} else if( direction === "x" ) {
var diffL = ev.clientX - initLeft + left,
scrollDiffPercent = diffL / scrollDiffWidth,
childMoveL = -scrollDiffPercent * childDiffWidth;
if (diffL < 0) {
scroll.css("left", 0);
child.css("margin-left", 0)
} else if (diffL > scrollDiffWidth) {
scroll.css("left", scrollDiffWidth);
child.css("margin-left", -childDiffWidth)
} else {
scroll.css("left", diffL);
child.css("margin-left", childMoveL);
}
}
});

$(document).bind("mouseup", function() {
$(document).unbind("mousemove")
});
});

parent.get(0).addEventListener("DOMMouseScroll", handleMouseWheel, false);
parent.get(0).addEventListener("mousewheel", handleMouseWheel, false);

function handleMouseWheel(ev) {
ev.preventDefault();
var scale = Math.max( - 1, Math.min(1, (ev.wheelDelta || -ev.detail))),
wheelHeight = scale * parent.height() * 0.618,
scrollTop = parseInt(scroll.css("top"));

if( scrollTop - wheelHeight < 0 ) {
scroll.css( "top", 0 );
child.css( "margin-top", 0 );
} else if(scrollTop - wheelHeight > scrollDiffHeight) {
scroll.css( "top", scrollDiffHeight );
child.css( "margin-top", -childDiffHeight );
$(document).unbind('mousemove');
} else {
var diffPercen = ( scrollTop - wheelHeight ) / scrollDiffHeight;
var childMove = - diffPercen * childDiffHeight;
scroll.css( "top", scrollTop - wheelHeight );
child.css( "margin-top", childMove );
}
}
return this
};

猜你喜欢

转载自blog.csdn.net/Deng_gene/article/details/75068379