DIV CSS 佈局教程網

用 JavaScript 做出淡藍色的滑鼠拖曳選擇框
編輯:關於JavaScript     

桌面系統裡「按住左鍵拖曳框選」的行為,在網頁上也能重現。這個範例用一個半透明的淡藍矩形跟著滑鼠畫出選取範圍,並把事件綁定與解除的細節都處理好了。

範例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>一個滑鼠選擇框</title>
<style type="text/css">
#rectBox {
    background: #CCFFFF;
    border: 2px solid #0099FF;
    filter: alpha(opacity=30);   /* 舊 IE */
    opacity: 0.3;
    position: absolute;
}
</style>

<script type="text/javascript">
function Rect() {
    this.doc = document.documentElement;
    if (!this.doc) return;
    this.startX = '';
    this.startY = '';
    this.rect = null;
    rectSelf = this;
}

// 按下:記錄起點並顯示矩形
Rect.prototype.down = function (e) {
    var e = e ? e : window.event;
    rectSelf.startX = e.clientX ? e.clientX + document.body.scrollLeft : e.pageX;
    rectSelf.startY = e.clientY ? e.clientY + document.body.scrollTop  : e.pageY;
    rectSelf.showRect(true);
};

// 放開:歸零並隱藏
Rect.prototype.up = function (e) {
    rectSelf.rectBox.style.width = '0px';
    rectSelf.rectBox.style.height = '0px';
    rectSelf.showRect(false);
};

// 移動:依起點與當前點算出寬高與左上角
Rect.prototype.move = function (e) {
    if (rectSelf.rectBox) {
        var currentX = e.clientX ? e.clientX + rectSelf.doc.scrollLeft : e.pageX;
        var currentY = e.clientY ? e.clientY + rectSelf.doc.scrollTop  : e.pageY;

        rectSelf.rectBox.style.width  = Math.abs(currentX - rectSelf.startX) + 'px';
        rectSelf.rectBox.style.height = Math.abs(currentY - rectSelf.startY) + 'px';

        // 往左上拖時,左上角要改抓當前座標
        if (currentX - rectSelf.startX < 0) {
            rectSelf.rectBox.style.left = currentX + 'px';
        }
        if (currentY - rectSelf.startY < 0) {
            rectSelf.rectBox.style.top = currentY + 'px';
        }
    }
};

Rect.prototype.showRect = function (bool) {
    if (bool) {
        if (!this.rectBox) {
            this.rectBox = document.createElement("div");
            this.rectBox.id = "rectBox";
            document.body.appendChild(this.rectBox);
        }
        this.rectBox.style.display = "block";
        this.rectBox.style.left = this.startX + 'px';
        this.rectBox.style.top  = this.startY + 'px';
        this.addEventListener(this.doc, 'mousemove', this.move);
    } else {
        if (this.rectBox) {
            this.rectBox.style.display = "none";
        }
        this.removeEventListener(this.doc, 'mousemove', this.move);
    }
};

// 事件綁定的跨瀏覽器封裝
Rect.prototype.addEventListener = function (o, e, l) {
    if (o.addEventListener) {
        o.addEventListener(e, l, false);
    } else if (o.attachEvent) {
        o.attachEvent('on' + e, function () { l(window.event); });
    }
};

Rect.prototype.removeEventListener = function (o, e, l) {
    if (o.removeEventListener) {
        o.removeEventListener(e, l, false);
    } else if (o.detachEvent) {
        o.detachEvent('on' + e, function () { l(window.event); });
    }
};

window.onload = function () {
    var oRect = new Rect();
    oRect.addEventListener(oRect.doc, 'mousedown', oRect.down);
    oRect.addEventListener(oRect.doc, 'mouseup',   oRect.up);
};
</script>
</head>
<body>
<h1>拖動你的滑鼠就會出現選擇框</h1>
</body>
</html>

三個關鍵設計

  1. 反向拖曳的處理:寬高用 Math.abs() 取絕對值,但當你往左上方拖時,矩形的最終位置應該是「當前點」而非起點,所以額外判斷負值並改寫 left/top。少了這段,反向選取會出現矩形跑錯位置的 bug。
  2. mousemove 只在拖曳期間綁定:在 down 時掛上、up 時移除,避免平時移動滑鼠就一直執行無意義的計算。
  3. 座標換算加上 scroll 偏移:clientX 是相對於視窗,加上 scrollLeft 才是文件座標,才能與 position: absolute 的定位對齊。

原範例的幾個問題

  • rectSelf = this 少寫 var,會變成全域變數,多實例時互相干擾。
  • detachEvent 傳錯參照:包成匿名函式後,解除時傳的是新函式,實際上移除不掉,會造成 mousemove 監聽洩漏。
  • 未阻止文字選取:拖曳時會把頁面文字一起選亮,需加上 e.preventDefault() 或 CSS 的 user-select: none。

現代改寫(Pointer Events)

(function () {
    var box = null;
    var startX = 0, startY = 0;
    var doc = document.documentElement;

    document.addEventListener('pointerdown', function (e) {
        if (e.button !== 0) return;          // 只處理左鍵

        startX = e.pageX;
        startY = e.pageY;

        box = document.createElement('div');
        box.className = 'rectBox';
        box.style.left = startX + 'px';
        box.style.top  = startY + 'px';
        document.body.appendChild(box);

        e.preventDefault();                  // 避免選取到文字
    });

    document.addEventListener('pointermove', function (e) {
        if (!box) return;

        var x = e.pageX, y = e.pageY;
        box.style.left   = Math.min(startX, x) + 'px';
        box.style.top    = Math.min(startY, y) + 'px';
        box.style.width  = Math.abs(x - startX) + 'px';
        box.style.height = Math.abs(y - startY) + 'px';
    });

    document.addEventListener('pointerup', function () {
        if (!box) return;
        box.remove();
        box = null;
    });
})();

用 Math.min() 取左上、Math.abs() 取寬高,比 if 判斷簡潔得多。Pointer Events 同時支援滑鼠、觸控與手寫筆,也不必再分 attachEvent 分支。

最後記得:真正要用這個框去「選取元素」,還需在 pointerup 時取得矩形範圍,再用 getBoundingClientRect() 逐一比對目標元素的相交情況。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved