如何将自定义滚动条应用于整个页面?

时间:2015-11-27 09:18:28

标签: javascript jquery html scroll scrollbar

我想在我的页面中加入Jquery custom content scroller以替换主滚动条。但由于某种原因,我无法让它发挥作用。

这是我的Codepen

它适用于一些较小的内容块但是如何将插件应用于主卷轴?

HTML

<canvas id="canvas"></canvas>

JS

(function($) {
  $(window).load(function() {
  $("canvas").mCustomScrollbar();
  });
})(jQuery);

1 个答案:

答案 0 :(得分:1)

您可以使用Nicescroll插件进行此操作。在html元素上添加:$("html").niceScroll();

此处有更多详情:http://areaaperta.com/nicescroll/

请尝试:

&#13;
&#13;
(function($) {
  $(window).load(function() {
  $("html").niceScroll();
  });
})(jQuery);

var timeOut;
window.onresize = function() {
  if (timeOut)
    clearTimeout(timeOut);
  timeOut = setTimeout(draw, 10);
}

window.onload = draw;
window.onscroll = navigate;

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

forest = new Image;
forest.src = 'http://p1.pichost.me/i/33/1561150.jpg';

function navigate() {
  draw()
}

function draw(scroll) {
  scroll = (window.scrollY || window.pageYOffset) / (document.body.clientHeight - window.innerHeight) * 3000;
  canvas.setAttribute('width', window.innerWidth);
  canvas.setAttribute('height', window.innerHeight);

  drawImageProp(ctx, forest, 0, (-scroll * 3.9) / 4, canvas.width, canvas.height + (scroll * 3.9) / 2);
}

function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {

  if (arguments.length === 2) {
    x = y = 0;
    w = ctx.canvas.width;
    h = ctx.canvas.height;
  }

  // default offset is center
  offsetX = typeof offsetX === "number" ? offsetX : 0.5;
  offsetY = typeof offsetY === "number" ? offsetY : 0.5;

  // keep bounds [0.0, 1.0]
  if (offsetX < 0) offsetX = 0;
  if (offsetY < 0) offsetY = 0;
  if (offsetX > 1) offsetX = 1;
  if (offsetY > 1) offsetY = 1;

  var iw = img.width,
    ih = img.height,
    r = Math.min(w / iw, h / ih),
    nw = iw * r, // new prop. width
    nh = ih * r, // new prop. height
    cx, cy, cw, ch, ar = 1;

  // decide which gap to fill
  if (nw < w) ar = w / nw;
  if (nh < h) ar = h / nh;
  nw *= ar;
  nh *= ar;

  // calc source rectangle
  cw = iw / (nw / w);
  ch = ih / (nh / h);

  cx = (iw - cw) * offsetX;
  cy = (ih - ch) * offsetY;

  // make sure source rectangle is valid
  if (cx < 0) cx = 0;
  if (cy < 0) cy = 0;
  if (cw > iw) cw = iw;
  if (ch > ih) ch = ih;

  // fill image in dest. rectangle
  ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);

}
&#13;
body {
  height: 1000vh;
  margin: 0;
} 

canvas {
  width: 100%;
  height: 100vh;
  position: fixed;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="view-source:http://areaaperta.com/nicescroll/js/jquery.nicescroll.min.js"></script>
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;