天天看點

基于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元立即加入學習!有需要的朋友戳:

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

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

繼續閱讀