孙肖宁

楼层跳跃的案例
描述:用户根据左侧的楼层号进行选择,点击左侧的楼层可以在整体页面进行跳转。示例代码:<!DOCTYPE ht...
扫描右侧二维码阅读全文
18
2018/04

楼层跳跃的案例

描述:用户根据左侧的楼层号进行选择,点击左侧的楼层可以在整体页面进行跳转。
示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>楼层跳跃</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body,html{
            height: 100%;
        }
        ul{
            list-style: none;
            height: 100%;
        }
        ul li{
            height: 100%;
        }
        ol{
            list-style: none;
            position: fixed;
            top: 80px;
            left: 50px;
        }
        ol li{
            width: 50px;
            height: 50px;
            border: 1px solid #000;
            text-align: center;
            line-height: 50px;
            margin-top: -1px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <ol>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ol>
</body>
</html>
<script>
    //获取相关元素
    var ul = document.getElementsByTagName("ul")[0];
    var ol = document.getElementsByTagName("ol")[0];
    var ulLiArr = ul.children;
    var olLiArr = ol.children;
    var target = 0;
    var leader = 0;
    var timer = null;
    //为方便给模块赋值颜色,定义一个颜色数组
    var arrColor = ["red","yellow","red","yellow","red"];
    /**
     * 循环绑定事件
     */
    for(var i = 0; i<arrColor.length;i++){
        //赋值颜色
        ulLiArr[i].style.background = arrColor[i];
        olLiArr[i].style.background = arrColor[i];
        //为ol里面的li添加索引
        olLiArr[i].index = i;
        //为ol里面的li设置点击事件
        olLiArr[i].onclick = function () {
            //设定目标值
            target = ulLiArr[this.index].offsetTop;
            clearInterval(timer);
            timer = setInterval(function () {
                var step = (target-leader)/10;
                step = step>0? Math.ceil(step):Math.floor(step);
                leader = leader+step;
                window.scrollTo(0,leader);
                if(Math.abs(target-leader)<=Math.abs(step)){
                    window.scrollTo(0,target);
                    clearInterval(timer);
                }
            },25);
        }
    }
    //把屏幕卷入的部分作为页面的起始值
    window.onscroll = function () {
        leader = scroll().top;
    }
    function scroll(){
        return {
            "top": window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop,
            "left":  window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft
        }
    }
</script>
Last modification:April 18th, 2018 at 01:58 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment