DIV CSS 佈局教程網

用 jQuery 實作拖曳元素改變大小尺寸
編輯:JQuery特效代碼     

「拖曳改變元素大小」其實和「拖曳元素」是同一個原理,只是動態改變的對象不同,重點在於 top、left、width、height 的運用,實作起來相當容易。以下附上原始碼,弄懂原理後再擴展成其他應用,思路就清晰多了。

<script type="text/javascript">
/*
* jQuery.Resize by wuxinxi007
* Date: 2011-5-14
*/
$(function(){
    //綁定需要拖曳改變大小的元素對象
    bindResize(document.getElementById('test'));
});

function bindResize(el){
    //初始化參數
    var els = el.style,
    //滑鼠的 X 和 Y 軸坐標
    x = y = 0;
    $(el).mousedown(function(e){
        //按下元素後,計算當前滑鼠與對象計算後的坐標
        x = e.clientX - el.offsetWidth,
        y = e.clientY - el.offsetHeight;
        //在支援 setCapture 的環境做些處理
        el.setCapture ? (
            el.setCapture(),                       //捕捉焦點
            el.onmousemove = function(ev){
                mouseMove(ev || event)
            },
            el.onmouseup = mouseUp
        ) : (
            $(document).bind("mousemove",mouseMove).bind("mouseup",mouseUp)
        )
        e.preventDefault() //防止默認事件發生
    });
    //移動事件
    function mouseMove(e){
        els.width = e.clientX - x + 'px',
        els.height = e.clientY - y + 'px'
    }
    //停止事件
    function mouseUp(){
        el.releaseCapture ? (
            el.releaseCapture(),                 //釋放焦點
            el.onmousemove = el.onmouseup = null  //移除事件
        ) : (
            $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp)
        )
    }
}
</script>

核心概念是:在 mousedown 時記下滑鼠座標與元素尺寸的差值,接著在 mousemove 時用「目前滑鼠座標 − 起始差值」算出新的 width 與 height,mouseup 時再解除綁定。這裡還用 setCapture/releaseCapture 處理了舊版 IE 的滑鼠捕捉行為,讓拖曳在邊界外也能正常運作。

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