HTML5 拖放及排序的简单实现

时间:2023-12-19 23:37:08

HTML5 拖放及排序的简单实现

之前写过个类似的例子,看这里.

但想再深入一步,希望能通过拖放,来交换二个元素的位置.最好有应用到手机平台上.

作了个简单的例子,在手机上测试的时候不成功..查了好多资料.暂时未能解决.

效果如下图:

相关代码如下:

html5 drag and drop : 在线演示查看源码

HTML :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title> html5 drag and drop</title>
         
    </head>
    <body>
        <div class="container">
            <a draggable="true"  id="a1" style='left:0px; '>one</a>
            <a draggable="true"  id="a2" style='left:160px; '>two</a>
            <a draggable="true"  id="a3" style='left:320px; '>three</a>
            <a draggable="true"  id="a4" style='left:480px; '>four</a>
            <a draggable="true"  id="a5" style='left:640px; '>five</a>
        </div>
        <script src="http://code.jquery.com/jquery-2.0.0.js"></script>
    </body>
</html>

JavaScript :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var origin;
$(".container").find("a").on("drop",
function(e) {
    var origin_pos = $(origin).position();
    var target_pos = $(e.target).position();
    $(origin).addClass("move").animate(target_pos, "fast",
    function() {
        $(this).removeClass("move");
    });
    $(e.target).addClass("move").animate(origin_pos, "fast",
    function() {
        $(this).removeClass("move");
    });
}).on("dragstart",
function(e) {
    // only dropEffect='copy' will be dropable
    e.originalEvent.dataTransfer.effectAllowed = 'move';
    origin = this;
}).on("dragover",
function(e) {
    if (e.preventDefault) e.preventDefault(); // allows us to drop
    e.originalEvent.dataTransfer.dropEffect = 'move'; // only dropEffect='copy' will be dropable
});

CSS :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
*[draggable=true] {
    -moz-user-select:none;
    -khtml-user-drag: element;
    cursor: move;
}
*:-khtml-drag {
    background-color: rgba(238,238,238, 0.5);
}
a {
    text-decoration: none;
    color: #000;
    width:120px;
  border: 3px dashed #999;
    padding: 10px;
    display:inline-block;
    transition: all 2s;
    position:absolute ;
    top:10px;
}
.container {
    position:relative;
}
a.move {
    -webkit-transform:scale3d( 1.1, 1.1, 1.1 );
}
a:hover:after {
    content: ' (drag me)';
    color: green }
Powered By RunJS