创建自定义滚动条

时间:2014-10-18 09:14:11

标签: javascript html css

我想使用纯JavaScript创建一个自定义滚动条,当我到达页面底部时,我遇到了使指针到达滚动条末端的问题。有没有办法在不使用jQuery的情况下做到这一点?

Fiddle

上的演示

HTML:

<div id="scroll-bar"></div>
<div id="pointer"></div>
<div class="test">first</div>
<div class="test"></div>
<div class="test"></div>
<div class="test">middle</div>
<div class="test"></div>
<div class="test"></div>
<div class="test">final</div>

的JavaScript:

var body = document.getElementsByTagName('body')[0];
var allDivs = document.getElementsByTagName('div');
var scrollBar = document.getElementById("scroll-bar");
var pointer = document.getElementById("pointer");
for (var i = 0; allDivs[i] != undefined; i++) {
  var last = i;
}
var pageHeight = allDivs[last].offsetHeight + allDivs[last].offsetTop;
pointer.style.top = "7%";

function setPosition(e) {
  var pos = e.screenY * 86;
  var move = pos / scrollBar.offsetHeight - 10;
  if (move > 7 && move < 89) {
    pointer.style.top = move + "%";
  }
  var scrollValue = move * pageHeight / 100;
  window.scrollTo(0, scrollValue);
}

function resetPosition() {
  scrollBar.removeEventListener('mousemove', setPosition);
  pointer.removeEventListener('mousemove', setPosition);
}
scrollBar.addEventListener('mousedown', function (event) {
  pointer.addEventListener('mousemove', setPosition);
  pointer.addEventListener('mouseup', resetPosition);
  scrollBar.addEventListener('mousemove', setPosition);
  scrollBar.addEventListener('mouseup', resetPosition);
});
scrollBar.addEventListener('click', function (event) {
  setPosition(event);
});
pointer.addEventListener('mousedown', function (event) {
  pointer.addEventListener('mousemove', setPosition);
  pointer.addEventListener('mouseup', resetPosition);
  scrollBar.addEventListener('mousemove', setPosition);
  scrollBar.addEventListener('mouseup', resetPosition);
});
body.addEventListener("mousewheel", function () {
  scrollBy(0, -window.event.wheelDelta);
});
body.addEventListener("DOMMouseScroll", function (e) {
  scrollBy(0, e.detail * 50);
});

CSS:

html {
    overflow: hidden;
}
.test {
    height: 100px;
    border-style: groove;
    border-width: 10px;
    border-color: red;
}
#scroll-bar {
    position: fixed;
    right: 0%;
    top: 7%;
    width: 3%;
    height: 86%;
    background-color: red;
}
#pointer {
    position: fixed;
    right: 0.5%;
    top: 7%;
    width: 2%;
    height: 4%;
    background-color: blue;
    z-index: 3;
}

0 个答案:

没有答案