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
增加一个按钮,可以关闭绘画效果,用来配合测试删除功能
//测试代码开始
//初始化
Rect.init("main");
document.getElementById('t').onclick = function(){
Rect.container.onmousedown = null;
};
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]