`

JS实现拖动效果

阅读更多

 来源:

 

     在闲暇之余实现了一个简单的JS拖动效果。下面是效果图:

     
 

 实现原理:

       编写鼠标按下(mousedown)、鼠标移动(mousemove)、鼠标释放(mouseup)的事件函数。为将被移动的元素(一般是div)注册mousedown事件,当被移动元素中的mousedown事件触发时为body注册mousemove和mouseup事件。当mouseup事件触发时,移除body的mousemove和mouseup事件。

 

代码如下:

 

 以下是JS代码:

<script type="text/javascript">

    window.onload = function(){
        result = $("result");
        $("center").onmousedown = moveFun;
    };

    /* 处理透明窗口移动 */
    function moveFun(event) {
        var body = document.documentElement,
            evt = event || window.event,
            src = evt.target || evt.srcElement;

        var _sX = 0, _sY = 0;

        if (evt.type === "mousedown" ) {
            body.onmousemove = moveFun;
            body.onmouseup = moveFun;

            window._offset_ = getElementOffset($("item"));
            _offset_ = {
                left : (evt.clientX - _offset_.left),
                top : (evt.clientY - _offset_.top)
            };
        }

        if (evt.type === "mousemove") {
            var target = $("item"),
                _x = evt.clientX,
                _y = evt.clientY;

            target.style.left = (_x - _offset_.left) + "px";
            target.style.top = (_y - _offset_.top) + "px";
        }

        if (evt.type === "mouseup" ) {
            body.onmousemove = null;
            body.onmouseup = null;
        }
    }

    /* 获取obj对象当前相当于窗口最左边和最上边的距离 */
    function getElementOffset(obj){
        var _left = obj.offsetLeft,
            _top = obj.offsetTop,
            parent = obj.offsetParent;

        while (parent != null) {
            _left += parent.offsetLeft;
            _top += parent.offsetTop;

            parent = parent.offsetParent;
        }

        return {
            left : _left,
            top : _top
        };
    }

    /* 返回指定id对象 */
    function $(id) {
        return document.getElementById(id);
    }
</script>

 

HTML代码:

<div class="item" id="item">
    <div class="center" id="center">
        <div class="content">
        人民日报发微博称,很多奶茶店热饮的杯盖上,都有一个三角符号,中间写着数字6。专家表示,最常用的6号塑料材料是聚苯乙烯,遇热可能会“放毒”,喝热饮最好不要带盖喝。这是怎么回事?6号塑料真的有毒吗?来看看本文怎么说吧。
        </div>
    </div>
    <div class="bottom">
        <a href="#" class="last">收藏</a>
        <img src="separator_updown.png">
        <a href="#">定时</a>
        <img src="separator_updown.png">
        <a href="#">发送</a>
    </div>
</div>

 

 

 

 

 

 

 

 

 

 

 

  • 大小: 230.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics