JavaScript拖拽图片四

现在用Firefox最新版本13.0测试,不work,图片会自动回到原位。

安装firebug扩展后调试一下。

到console窗口点击enable后,

错误信息是:

window.event is undefined.

Firefox不支持window.event,因此所有用到event的地方要类似这样写:

function mouseDown(e) {
	'use strict';
	e = e || window.event;//必须这样写
	window.dragObj = e.currentTarget || e.srcElement;
	if (window.dragObj !== null) {
		window.clickLeft = e.x - parseInt(window.dragObj.style.left, 10);
		window.clickTop = e.y - parseInt(window.dragObj.style.top, 10);
		window.dragObj.style.zIndex += 1;
	}
}

解决了这个错误后,测试一下Chrome和IE6,都工作正常,但是Firefox仍然不行。鼠标左键松开的时候,图片仍然跟着跑。

注意,在Ubuntu12.04+FireFox13.0+FireBug1.9下,debug很容易让Firefox死掉。

这个问题是因为Firefox的mouseUp事件没有被触发。用下面的代码可以解决,在mouseDown函数中,添加:

	if(e.preventDefault) {
		e.preventDefault();
	}else {
		e.returnValue = false;
	}
这样mouseUp事件就能正常触发了。重构一下代码,再用jslint4java扫描一下,解决了书写格式后。现在一份同时兼容IE6 sp3, Firefox13.0,Chrome的代码出现了:

/*global window */

function getEvent(e) {
	'use strict';
	return e || window.event;
}

function getTarget(e) {
	'use strict';
	return e.currentTarget || e.srcElement;
}


function getPos(e) {
	'use strict';
	return {
		x: e.x || e.clientX,
		y: e.y || e.clientY
	};
}


function mouseDown(e) {
	'use strict';
	e = getEvent(e);
	window.dragObj = getTarget(e);
	if (e.preventDefault) {
		e.preventDefault();
	} else {
		e.returnValue = false;
	}
	if (window.dragObj !== null) {
		var pos = getPos(e);
		window.clickLeft = pos.x - parseInt(window.dragObj.style.left, 10);
		window.clickTop = pos.y - parseInt(window.dragObj.style.top, 10);
		window.dragObj.style.zIndex += 1;
	}
}

/**
 * IE6.0 need this
 */
function mouseStop(e) {
	'use strict';
	e = getEvent(e);
	e.returnValue = false;
}

function mouseMove(e) {
	'use strict';
	e = getEvent(e);
	if (window.dragObj !== null) {
		var pos = getPos(e);
		window.dragObj.style.left = pos.x - window.clickLeft;
		window.dragObj.style.top = pos.y - window.clickTop;
	}
}

function mouseUp() {
	'use strict';
	window.dragObj = null;
}

function init() {
	'use strict';
	window.dragObj = null;
	window.document.onmousemove = mouseMove;
	window.document.onmouseup = mouseUp;
	window.document.ondragstart = mouseStop;
}

做前端真的不容易啊。我还没有测试IE7,8,9呢!




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值