解决方法
最简单的概念是使用jQuery UI draggable并将.draggable()方法附加到.scrollbar
var $scrollable = $(".scrollable"),$scrollbar = $(".scrollbar"),height = $scrollable.outerHeight(true),// visible height scrollHeight = $scrollable.prop("scrollHeight"),// total height barHeight = height * height / scrollHeight; // Scrollbar height! // Scrollbar drag: $scrollbar.height( barHeight ).draggable({ axis : "y",containment : "parent",drag: function(e,ui) { $scrollable.scrollTop( scrollHeight / height * ui.position.top ); } }); // Element scroll: $scrollable.on("scroll",function() { $scrollbar.css({top: $scrollable.scrollTop() / height * barHeight }); });
.parent{ position:relative; overflow:hidden; height:200px; width:180px; background:#ddd; } .scrollable{ overflow-y:scroll; position:absolute; padding:0 17px 0 0; width: 180px; height:100%; } .scrollbar{ cursor:n-resize; position:absolute; overflow:auto; top:0px; right:0px; z-index:2; background:#444; width:17px; border-radius:8px; }
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/ui/1.11.0/jquery-ui.min.js"></script> <div class="parent"> <div class="scrollbar"></div> <div class="scrollable"> Lorem ipsum dolor sit amet,consectetur adipiscing elit. Cras non nunc eget sapien molestie mollis. Proin vestibulum vehicula varius. Duis a nunc ac risus facilisis consectetur. Lorem ipsum dolor sit amet,consectetur adipiscing elit. Cras non nunc eget sapien molestie mollis. Proin vestibulum vehicula varius. Duis a nunc ac risus facilisis consectetur. Lorem ipsum dolor sit amet,consectetur adipiscing elit. Cras non nunc eget sapien molestie mollis. Proin vestibulum vehicula varius. Duis a nunc ac risus facilisis consectetur. </div> </div>