自定义可滚动div将卷轴保留在容器中

时间:2013-10-01 16:34:24

标签: javascript

我正在尝试创建自定义div滚动条。

See DEMO

如此接近!如何将卷轴保持在容器的范围内?

我正在努力避免像jQuery这样的JavaScript库。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        #content {
            height: 500px;
            width: 500px;
            overflow: hidden;
            border: solid 1px red;
        }

        #scr {
            height: 100px;
            width: 100px;
            top: 100px;
            left: 50px;
            position: absolute;
            border: solid 1px black;
            background-color: #26a0eb;
            z-index: 3;

        }       
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div id="content" style="margin-top:100px;">
            <div id="scr">
            </div>

            <div id="container">
              see demo above for scrollable content
            </div>

        </div>
    </form>

    <script type="text/javascript">

        window.onload = function () {
            //help from http://stackoverflow.com/a/13152737/139698
            draggable('scr');
        };

        var dragObj = null;
        function draggable(id) {
            var obj = document.getElementById(id);
            obj.style.position = "absolute";
            obj.onmousedown = function () {
                dragObj = obj;
            }
        }

        document.onmouseup = function (e) {
            dragObj = null;
        };

        document.onmousemove = function (e) {
            var y = e.pageY;  //scroller

            if (dragObj == null)
                return;

            var c = document.getElementById('content');
            //var b = document.getElementById('scrbox');       
                /*
                1. scr.top - scrbox.top = x
                2. x / scrbox height = pct
                3. scroll top = scroll height * pct
                */

                var x = y - c.offsetTop;
                var pct = x / c.clientHeight;
                c.scrollTop = Math.floor(c.scrollHeight * pct);


                dragObj.style.top = (y-50) + 'px'; //50 is an offset                
        };
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

在某些浏览器中无法在触摸屏上使用,使用touchbegin,touchmove,touchend事件来改善触摸支持,也尽量使用尽可能多的静态定位,绝对或相对定位会导致滚动时性能下降。我还推荐车轮支撑