JS 流行库(四):iScroll
iScroll 是一个高性能、资源占用少、无依赖、跨平台的 JavaScript 滚动插件
基本使用
- 导入 iScroll 库
示例如下:
<script src="./iscroll.js"></script>
- HTML 结构
示例如下:
<div class="wrapper">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
</div>
- JavaScript 代码
示例如下:
window.onload = function () {
let myScroll = new IScroll(".wrapper");
}
在上述示例中,将包含菜单的 div 的 class 传入了 IScroll 构造函数中,也可以传入元素的 id 属性等
高级使用
配置
在 IScroll 构造函数中可以传入选项以配置 iScroll 实例,常用的配置项如下:
- mouseWheel
- scrollbars
示例如下:
window.onload = function () {
let myScroll = new IScroll(".wrapper", {
mouseWheel: true,
scrollbars: true
});
}
在上述示例中,为 .wrapper 添加滚动条时,必须为 .wrapper 在 CSS 中添加定位属性,示例如下:
.wrapper {
width: 300px;
height: 90px;
border: 1px solid black;
box-sizing: border-box;
margin: 100px auto;
overflow: hidden;
position: relative;
}
为 .wrapper 添加滚动条时,iScroll 可以自定义滚动条的样式,此时必须将 scrollbars 属性的值设置为 custom,示例如下:
window.onload = function () {
let myScroll = new IScroll(".wrapper", {
mouseWheel: true,
scrollbars: "custom"
});
}
之后可以在 CSS 中自定义样式,类名如下:
- iScrollVerticalScrollbar
- iScrollIndicator
示例如下:
.iScrollVerticalScrollbar {
width: 6px;
height: 85px;
background-color: white;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
z-index: 1024;
border: 1px solid black;
box-sizing: border-box;
border-radius: 2px;
}
.iScrollIndicator {
width: 4px;
background-color: black;
border-radius: 2px;
}
自定义事件
iScroll 包含了若干自定义事件,常用事件如下:
事件 | 描述 |
---|---|
beforeScrollStart | 在用户触摸屏幕但还没有开始滚动时触发 |
scrollStart | 开始滚动 |
scroll | 内容滚动时触发,仅在 scroll-probe.js 版本中有效 |
scrollEnd | 停止滚动时触发 |
示例如下:
window.onload = function () {
let myScroll = new IScroll(".wrapper", {
mouseWheel: true,
scrollbars: "custom"
});
myScroll.on("beforeScrollStart", function () {
console.log("before"); // before
});
myScroll.on("scrollStart", function () {
console.log("start"); // start
});
myScroll.on("scrollEnd", function () {
console.log("stop"); // stop
});
}
在上述示例中,由于 scroll 事件仅在 scroll-probe.js 版本有效,所以未演示