javascript获取事件源

阅读更多

javascript获取事件源

var node = evt.currentTarget || evt.srcElement;
var obj = event.srcElement ? event.srcElement : event.target;

 

加强版:

var eventTarget = event.srcElement || event.target || event.toElement|| event.currentTarget

 范例:

var event = window.event || ev;//兼容ie7 8
            cleanUpDefaultEvent(event);//清除默认事件
            var target2 = event.srcElement || event.target || event.toElement;
            var position = {x: 0, y: 0};
            var imgObj = target2;

 

getRelativePosition = helpers.getRelativePosition = function(evt){
			var mouseX, mouseY;
			var e = evt.originalEvent || evt,
				canvas = evt.currentTarget || evt.srcElement||evt.target||evt.toElement,
				boundingRect = canvas.getBoundingClientRect();

			if (e.touches){
				mouseX = e.touches[0].clientX - boundingRect.left;
				mouseY = e.touches[0].clientY - boundingRect.top;

			}
			else{
				mouseX = e.clientX - boundingRect.left;
				mouseY = e.clientY - boundingRect.top;
			}

			return {
				x : mouseX,
				y : mouseY
			};

		}

  

封装成为函数:

/***
 * 获取事件源
 * @param evt
 * @returns {*|Object}
 */
getSrcElement = function (evt) {
    var event = window.event || evt;//兼容ie7 8
    var eventTarget = event.srcElement || event.target || event.toElement || event.currentTarget;
    return eventTarget;
};

 

 

 

你可能感兴趣的:(获取事件源,srcElement,event.target)