基於HTML5的移動Web應用——拖曳

自鼠標被髮明以來,拖曳操作在計算機的操作中無處不在。例如,移動文件、圖片處理等都需要拖曳。但是如此常見的操作,在Web世界只能通過模擬方式來實現。

在HTML5的規範中,可以通過爲元素增加draggable= "true"來設置此元素是否可以進行拖曳操作,很大程度上簡化了拖曳交互的難度。其中圖片、鏈接默認是開啓的。

在HTML5的拖曳操作中,首先要明確拖曳元素和目標元素。
(1)拖曳元素:即頁面中設置了draggable=“rue” 屬性的元素。
(2)目標元素:頁面中任何一個元素都可以成爲目標元素。
在HTML5中提供了關於拖曳元素和目標元素的事件監聽,如表所示。

表1 應用於拖曳元素的事件監聽

方法 描述
ondrag() 整個拖曳過程都會調用
ondragstart() 當拖曳開始時調用
ondragleave() 當鼠標離開拖曳元素時調用
ondragend() 當拖曳結束時調用

表2 應用於目標元素的事件監聽

方法 描述
Ondragenter 當拖曳元素進入時調用
ondragover 當停留在目標元素上時調用
ondrop 當在目標元素上鬆開鼠標時調用
ondragleave 當鼠標離開目標元素時調用

下面通過一個案例來演示HTML5中的拖曳操作,代碼如示例所示。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖曳</title>
    <style>
        body {
            padding: 0;
            margin: 0;
            background-color: #F7F7F7;
            position: relative;
        }
        .box {
            width: 150px;
            height: 150px;
            background-color: yellow;
            position: absolute;
            top: 100px;
            left: 50px;
        }

        .container {
            width: 300px;
            height: 300px;
            background-color: green;
            position: absolute;
            top: 100px;
            left: 50%;
            margin-left: -150px;
        }
    </style>
</head>
<body>
<div class="box" draggable="true"></div>
<div class="container"></div>

<script>
    var box = document.querySelector('.box');
    var container = document.querySelector('.container');
    // 整個拖拽都會執行
    box.addEventListener('drag', function () {
        console.log(1);
    });
    box.addEventListener('dragleave', function () {
        console.log(2);
    });

    // 拖拽開始
    box.addEventListener('dragstart', function () {
        this.style.backgroundColor = 'pink';
        console.log(3)
    });

    // 拖拽結束
    box.addEventListener('dragend', function (ev) {
        this.style.backgroundColor = '';
        // console.log(ev);
    });

    // 進入到目標
    container.addEventListener('dragenter', function () {
        this.style.backgroundColor = 'pink';
    });

    // 在目標元素上移動
    container.addEventListener('dragover', function (ev) {
        this.style.backgroundColor = 'yellow';
        ev.preventDefault();
    });

    //
    container.addEventListener('drop', function (ev) {
        this.style.backgroundColor = 'black';
        console.log(ev);
        ev.preventDefault();
    });
</script>
</body>
</html>

在上述代碼中,首先準備兩個盒子:box爲拖曳元素,container爲目標元素。
用Chrome瀏覽器訪問示例,並按[F12] 鍵打開瀏覽器的控制檯。
在示例中,設置了從拖曳開始、移動、進入目標的一系列監聽,讀者可以根據控制檯打印的數據來感受監聽過程。因爲在書本中無法打印出顏色的變化,這裏就不做過多的說明,該案例要求讀者仔細在計算機上實踐觀察。


超全面的測試IT技術課程,0元立即加入學習!有需要的朋友戳:


騰訊課堂測試技術學習地址

歡迎轉載,但未經作者同意請保留此段聲明,並在文章頁面明顯位置給出原文鏈接。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章