Thursday, December 4, 2008

自定义滚动条

用法
给需要添加滚动条的 div 添加 class "autoscroller",设置模块高度。
注意,这个 div 只可以包含一个子节点。
html
<div style="height:100px;" class="autoscroller"> <div style="height:150px;"></div> </div> css
.autoscroller{position:relative;overflow:hidden;} .autoscroller .scrollcon{overflow:hidden;} .autoscroller .scrollbar{ position:absolute;right:0;top:0;width:9px; background:#fff;font-size:1px;line-height:1px;} .autoscroller .scrollbar s{ position:absolute;left:3px;top:0;height:100%;width:2px; border-left:1px solid #c3c3c3;background:#000;} .autoscroller .scrollbar i{ width:9px;position:absolute; background:url(scroller_btn.gif) repeat-y 0 0; cursor:n-resize;left:0;top:0;} .autoscroller .scrollbar i b{ background:url(scroller_btn.gif) no-repeat -9px 0; display:block;padding:4px 0 0;} .autoscroller .scrollbar i b b{background-position:-18px 100%;padding:0 0 4px;} .autoscroller .scrollbar i b b b{background-position:100% 50%;}

img

js
//require: jquery, drag, wheel function fix_scrollers(){ var j = jQuery; /* .autoscroller .scrollcon .scrollbar s i b b b*/ j('.autoscroller').each(function(idx, sc){ sc = j(sc); var con = j('<div class="scrollcon"/>').appendTo(sc), con0 = con[0]; con.append(sc.find('>*:first')); var h = [sc[0].offsetHeight, con0.scrollHeight]; if(h[0] - h[1] >= 0)return; var bar = j('<div class="scrollbar"></div>').appendTo(sc), btn = bar.find('>i'); con.css('height', h[0] + 'px'); bar.css('height', h[0] + 'px'); bar.find('>s').css('height', h[0] + 'px'); j(j.dir(btn[0], 'firstChild').pop()).css('height', Math.max(0, (h[0] * h[0] / h[1]) - 8) + 'px'); var btnYA = [0, bar[0].offsetHeight - btn[0].offsetHeight]; var sRate = Math.min(1, btnYA[1] / (h[1] - h[0])), wheelPH = -25 * sRate; var drag_posY = null, drag_top = null; btn.bind('dragstart',function(ev){ drag_posY = ev.offsetY; drag_top = parseInt(btn.css('top')) || 0; }) .bind('drag',function(ev){ var offsetY = ev.offsetY - drag_posY; var top = Math.max(btnYA[0], Math.min(btnYA[1], drag_top + offsetY)); this.style.top = top + 'px'; con0.scrollTop = top / sRate; }); sc.mousewheel(function(ev, delta){ var btnTop = parseInt(btn.css('top')) || 0; if((btnTop==btnYA[0] && delta > 0) || (btnTop==btnYA[1] && delta < 0))return true; btnTop = Math.max(btnYA[0], Math.min(btnYA[1], btnTop + delta * wheelPH)); btn[0].style.top = btnTop + 'px'; con0.scrollTop = btnTop / sRate; return false; }); }); }