JS 流行库(四):iScroll

JS 流行库(四):iScroll

iScroll 是一个高性能、资源占用少、无依赖、跨平台的 JavaScript 滚动插件

基本使用

  1. 导入 iScroll 库

示例如下:

<script src="./iscroll.js"></script>
  1. 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>
  1. 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 版本有效,所以未演示

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值