我正在考虑制作自定义滚动条jQuery插件,有很多插件可用,但我想自己创建,问题是我没有得到如何通过移动其他div元素移动内容的概念(滚动条)以及如何使用鼠标滚动器移动内容?
请帮助我理解这一点。
由于
答案 0 :(得分:32)
最简单的概念是使用可拖动的jQuery UI并将.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.
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>
&#13;
以上只是涉及所需逻辑和数学的一个例子,
它错过了&#34; hide-scrollbar&#34;,只是为了保持简单。我将留给您添加所有需要的调整,插件。
答案 1 :(得分:0)
使自定义滚动条不使用jQuery-UI 。
HTML: -
[self layoutIfNeeded]
<强> CSS: - 强>
<div class="parent">
<div class="scrollbar"></div>
<div class="scrollable">
<p>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.</p>
</div>
</div>
<强>使用Javascript: - 强>
.parent{
position:relative;
margin:50px;
overflow:hidden;
height:200px;
width:180px;
background:#ddd;
}
.scrollable{
overflow-y:scroll;
position:absolute;
padding:0 17px 0 0;
width: 180px;
height:100%;
}
.scrollbar{
position:absolute;
overflow:auto;
top:0px;
right:0px;
z-index:2;
background:#444;
width:7px;
border-radius:5px;
}