用鼠标不断调整元素大小的最佳方法是什么?

What's the best way of constantly resizing elements with the mouse?

本文关键字:最佳 方法 是什么 鼠标 调整 元素      更新时间:2023-09-26

使用点击并按住元素右下角的调整大小图像来不断调整元素大小的最佳方法是什么?是否有一个特定的空元素,有调整大小内置或样式使用,将比在JavaScript中使用while循环更好?

给你:

http://jsfiddle.net/d9hsG/

function c(a){console.log(a)}
function coords(el){
    var curleft, curtop;
    curleft=curtop=0;
    do{
        curleft+=el.offsetLeft;
        curtop+=el.offsetTop;
    } while(el=el.offsetParent);
    return [curleft,curtop];
}
Resizer = {
    attach: function(el,minh,minw){
        var rs=el.resizer=el.getElementsByClassName('drag')[0];
        rs.resizeParent=el;
        if(minh==undefined){
            el.minh=rs.offsetHeight*2;
        }
        if(minw==undefined){
            el.minw=rs.offsetWidth*2;
        }
        rs.onmousedown = Resizer.begin;

    },
    begin: function(e){
        var el=Resizer.el=this.resizeParent;
        var e=e||window.event;
        this.lastx=e.clientX;
        this.lasty=e.clientY;
        document.onmousemove=Resizer.resize;
        document.onmouseup=Resizer.end;
        return false;

    },
    resize: function(e){
        var e = e || window.event;
        var x,y,mx,my,el,rs,neww,newh;
        el=Resizer.el;
        rs=el.resizer;
        mx=e.clientX;
        my=e.clientY;
        neww=(el.clientWidth-(rs.lastx-mx));
        newh=(el.clientHeight-(rs.lasty-my));
        if(neww>=el.minw){     
            el.style.width=neww+'px';
            rs.lastx=mx;
        }
        else{
            rs.lastx-=parseInt(el.style.width)-el.minw;
            el.style.width=el.minw+'px';
        }
        if(newh>=el.minh){
            el.style.height=newh+'px';
            rs.lasty=my;
        }
        else{
            rs.lasty-=parseInt(el.style.height)-el.minh;
            el.style.height=el.minh+'px';
        }
        return false;

    },
    end: function(){
        document.onmouseup=null;
        document.onmousemove=null;
    }
};
window.onload=function(){
    Resizer.attach(document.getElementsByClassName('resize')[0]);
}

你的HTML需要看起来像:

<div class="resize"><
    div class="drag"></div>
</div>

这两个元素都不需要是div,但是可缩放元素的类需要是"resize",可拖动元素的类需要是"drag"。

附加:

Resizer.attach(element);

…其中元素是要调整大小的元素。

作用于多个元素,如jsfiddle所示。您还可以传入最小高度和最小宽度。如果你不这样做,它会自动使它们的高度是可拖动元素的两倍。

当你向下滚动时,它目前确实有一个问题。

我不知道如何解决这个问题,但我以后会再做的。

一般的方法是这样的:

  • 当onmousedown触发调整大小目标时,开始跟踪onmousemove
  • 当onmousmove触发时,调整元素的大小
  • 当onmouseup触发时,清除onmousemove处理程序

所以基本上你只是响应事件,没有while循环或其他相关的东西

这可能有点棘手,以实现它很好地工作,所以我建议看看是否有一个JS库你可以使用。获得这种行为的一个非常简单的方法是使用jQuery UI的可调整大小组件