用鼠标不断调整元素大小的最佳方法是什么?
What's the best way of constantly resizing elements with the mouse?
使用点击并按住元素右下角的调整大小图像来不断调整元素大小的最佳方法是什么?是否有一个特定的空元素,有调整大小内置或样式使用,将比在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的可调整大小组件
相关文章:
- 有条件更新d3.js力图中节点的最佳方法
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- 从数组中删除元素的最佳方法是:javascript/jquery
- 以编程方式填充组合框道场 (1.8) 的最佳方法是什么?
- 列出没有 mysql 的元素的最佳方法是什么
- 在jquery库中重新定义方法的最佳方法
- Javascript,用vars创建对象的最佳方法
- 使用 jQuery 从 HTML 中获取某些值的最佳方法
- 在变量中保存值的最佳方法是在应用程序关闭后使用,然后使用apachecordova在android中重新启动
- 在d3.json中使用d3.csv组合多个csv文件数据输入的最佳方法是什么
- 用jasmine测试JavaScriptUI的最佳方法
- 使用javascript:在没有阻止html标记(<b>、<p>等)的情况下,阻止脚本的最佳方法
- 如果我返回表,检查 Ajax 调用是否为 200 OK的最佳方法是什么
- JavaScript - 创建可链接函数时的最佳方法是什么
- 在上下文菜单项单击上显示侧边栏/弹出窗口的最佳方法是什么
- 在 JavaScript 中获取范围的随机数的最佳方法
- 在对象类上实现 jquery 作用域的最佳方法
- 将同步函数包装到承诺中的最佳方法是什么?
- 使用 MVC 删除 JavaScript 中硬编码字符串 Asp.Net 最佳方法