HTML5:在X轴上拖放而不褪色?

时间:2012-01-19 21:26:32

标签: javascript html5

我一直在寻找HTML5的拖放示例/教程,但到目前为止所有这些都涉及一个对象,它会被拖动而不受任何轴约束。我想知道是否可以拖动实际物体本身而不是它的鬼魂以及我是否可以将它约束到X轴或Y轴?

谢谢!

1 个答案:

答案 0 :(得分:18)

是的,很容易,自己写一下。

elem.onmousedown = function(e) {
    e = e || window.event;
    var start = 0, diff = 0;
    if( e.pageX) start = e.pageX;
    else if( e.clientX) start = e.clientX;

    elem.style.position = 'relative';
    document.body.onmousemove = function(e) {
        e = e || window.event;
        var end = 0;
        if( e.pageX) end = e.pageX;
        else if( e.clientX) end = e.clientX;

        diff = end-start;
        elem.style.left = diff+"px";
    };
    document.body.onmouseup = function() {
        // do something with the action here
        // elem has been moved by diff pixels in the X axis
        elem.style.position = 'static';
        document.body.onmousemove = document.body.onmouseup = null;
    };
}