懂视1
懂视101
懂视201
懂视301
懂视401
懂视501
懂视601
懂视701
懂视801
懂视901
懂视1001
懂视1101
懂视1201
懂视1301
懂视1401
懂视1501
懂视1601
懂视1701
懂视1801
懂视1901
文库1
文库101
文库201
文库301
文库401
文库501
文库601
文库701
文库801
文库901
文库1001
文库1101
文库1201
文库1301
文库1401
文库1501
文库1601
文库1701
文库1801
文库1901
非凡科技
全部频道
首页
科技
教育
生活
旅游
时尚
美容
美食
健康
体育
游戏
汽车
家电
您的当前位置:
首页
javascript绘制矩形框_javascript技巧
javascript绘制矩形框_javascript技巧
来源:非凡科技
如果不考虑把整个代码封装起来, 大约5分钟里也可以写出类似的效果,为了把整个代码封装成一个对象,稍微借鉴了Pro Javascript Techniques书中的代例子的风格。
Pro Javascript Techniques书中推荐的drag and drop 例子:http://boring.youngpup.net/2001/domdrag
Rect
var Rect = { //当前正在画的矩形对象 obj: null, //画布 container: null, //初始化函数 init: function(containerId){ Rect.container = document.getElementById(containerId); if(Rect.container){ //鼠标按下时开始画 Rect.container.onmousedown = Rect.start; } else{ alert('You should specify a valid container!'); } }, start: function(e){ var o = Rect.obj = document.createElement('div'); o.style.position = "absolute"; // mouseBeginX,mouseBeginY是辅助变量,记录下鼠标按下时的位置 o.style.left = o.mouseBeginX = Rect.getEvent(e).x; o.style.top = o.mouseBeginY = Rect.getEvent(e).y; o.style.height = 0; o.style.width = 0; o.style.border = "dotted black 1px"; //向o添加一个叉叉,点击叉叉可以删除这个矩形 var deleteLink = document.createElement('a'); deleteLink.href="#"; deleteLink.onclick = function(){ Rect.container.removeChild(this.parentNode); //this.parentNode.style.display = "none"; //alert(this.tagName); } deleteLink.innerText = "x"; o.appendChild(deleteLink); //把当前画出的对象加入到画布中 Rect.container.appendChild(o); //处理onmousemove事件 Rect.container.onmousemove = Rect.move; //处理onmouseup事件 Rect.container.onmouseup = Rect.end; }, move: function(e){ var o = Rect.obj; //dx,dy是鼠标移动的距离 var dx = Rect.getEvent(e).x - o.mouseBeginX; var dy = Rect.getEvent(e).y - o.mouseBeginY; //如果dx,dy <0,说明鼠标朝左上角移动,需要做特别的处理 if(dx<0){ o.style.left = Rect.getEvent(e).x; } if(dy<0){ o.style.top = Rect.getEvent(e).y; } o.style.height = Math.abs(dy); o.style.width = Math.abs(dx); }, end: function(e){ //onmouseup时释放onmousemove,onmouseup事件句柄 Rect.container.onmousemove = null; Rect.container.onmouseup = null; Rect.obj = null; }, //辅助方法,处理IE和FF不同的事件模型 getEvent: function(e){ if (typeof e == 'undefined'){ e = window.event; } //alert(e.x?e.x : e.layerX); if(typeof e.x == 'undefined'){ e.x = e.layerX; } if(typeof e.y == 'undefined'){ e.y = e.layerY; } return e; } }; script> 增加一个按钮,可以关闭绘画效果,用来配合测试删除功能
//测试代码开始 //初始化 Rect.init("main"); document.getElementById('t').onclick = function(){ Rect.container.onmousedown = null; }; script>
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
显示全文