事件对象

  • 三个重要坐标
    document.onclick = function (event) {
        //var event = event || window.event;
        var event = eventUtil.getEvent(event);
        console.log("client: " + event.clientX + "--" + event.clientY);//浏览器窗口
        //page有兼容问题 client没有 我们可以用client来计算page
        var pageX = eventUtil.getPageX(event);
        var pageY = getPageY(event);
        console.log("page: " + event.pageX + "--" + event.pageY);//页面上,如果页面有滚出也要加上
        console.log("screen: " + event.screenX + "--" + event.screenY);//整个屏幕
    };
    //其中 最常用的是page

    function getPageX(event) {
        return event.pageX || event.clientX + document.documentElement.scrollLeft;
    }
    function getPageY(event) {
        return event.pageY || event.clientY + document.documentElement.scrollTop;
    }
  • 计算鼠标在盒子中的位置

  • 阻止事件冒泡



    
    






封装

  • even 对象封装
var eventUtil = {
    getEvent: function (event) {
        return event || window.event;
    },
    getPageX: function (event) {
        return event.pageX || event.clientX + document.documentElement.scrollLeft;
    },
    getPageY: function (event) {
        return event.pageY || event.clientY + document.documentElement.scrollTop;
    },
    stopPropagation: function (event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        } else {
            event.cancelBubble = true;
        }
    },
    getTarget: function (event) {
        return event.target || event.srcElement;
    }
};

你可能感兴趣的:(事件对象)