我正在编写一个滚动条来替换浏览器上的滚动条。我更喜欢自己学习,而不是使用jQuery。
我有这个代码可以工作,但我有几个问题:
HTML:
<div id="portfolioScrollbar">
<div id="scrollbarTrack"><a id="scrolla" href="#scrollbar"></a></div>
<div id="pbody">
...all the text stuff...
</div>
</div>
编辑新代码1/27/2013:
Javscript:
function CloseContact() {
setTimeout (addClose, 2200 );
setTimeout (addContact, 2400 );
var foo = document.getElementById("scrolla");
foo.addEventListener( "mousedown", scrollObject.sbar1, false);
foo.addEventListener( "mouseup", removeAll, false);
foo.addEventListener( "mouseout", removeAll, false);
}
function removeAll(event) {
console.log("REMOVEaLL");
var foo = document.getElementById("scrolla");
foo.removeEventListener("mouseup", scrollObject.sbar2, false);
foo.removeEventListener("mouseout", scrollObject.sbar2, false);
foo.removeEventListener("mousemove", scrollObject.sbar2, false);
}
var scrollObject = function (event) {
var current = 0;
var move = null;
function sbar1(event) {
console.log("mousedown");
event.preventDefault();
var foo = document.getElementById("scrolla");
current = event.clientY;
foo.addEventListener( "mousemove", sbar2, false);
}
function sbar2(event) {
// console.log(event.clientY);
event.preventDefault();
var pbody = document.getElementById("pbody");
var scroll = document.getElementById("scrolla");
move = event.clientY - current;
if (move != 78644 ) {
console.log(move);
scroll.style.marginTop = move + "px";
//current = move;
}
}
return {
sbar1: sbar1,
sbar2: sbar2,
}
}();
答案 0 :(得分:1)
ķ。所以问题是,您正在调整边距以匹配单击的高度,这会将滚动条的边缘设置为鼠标的位置。这会立即触发mouseout处理程序,从而删除滚动处理程序。
我在代码中添加了一些日志记录,如下所示:
<script type="text/javascript">
var foo = document.getElementById("scrolla");
var pbody = document.getElementById("pbody");
var scroll = document.getElementById("scrolla");
function contact() {
foo.addEventListener( "mousedown", sbar1, false);
foo.addEventListener( "mouseup", function() { console.log("### removing mousemove"); foo.removeEventListener("mousemove", sbar2, false) }, false);
foo.addEventListener( "mouseout", function() { console.log("### removing mouseout"); foo.removeEventListener("mousemove", sbar2, false) }, false);
}
function sbar1() {
console.log("@@@ adding listener");
foo.addEventListener( "mousemove", sbar2, false);
}
function sbar2(event) {
console.log("moving");
var h = event.clientY;
console.log(h);
scroll.style.marginTop = h + "px";
}
scroll.addEventListener('click', contact, false);
contact();
</script>
最终点击了以下输出:
@@@ adding listener
moving
67
### removing mouseout
### removing mousemove
我会让你探索你当前的方法,但你可能想要计算鼠标在拖动上的位置差异,而不是直接将滚动条移动到鼠标的位置。
例如,当他们最初点击时,您存储clientY的值。然后,当他们向上或向下移动鼠标时,您将新的clientY与初始clientY进行比较,并将差异应用于滚动条的margin-top。
听起来不错?