我想在页面中包含Jquery custom content scroller以便替换主滚动条。但是由于某种原因,我无法使其正常运行。
这是我的Codepen。
它适用于一些较小的内容块,但是如何将插件应用于主滚动条?
的HTML
<canvas id="canvas"></canvas>
JS
(function($) {
$(window).load(function() {
$("canvas").mCustomScrollbar();
});
})(jQuery);
最佳答案
您可以使用Nicescroll
插件来做到这一点。使用html
在$("html").niceScroll();
元素上添加此元素
此处有更多详细信息:http://areaaperta.com/nicescroll/
请试试:
(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);
}
body {
height: 1000vh;
margin: 0;
}
canvas {
width: 100%;
height: 100vh;
position: fixed;
}
<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>