怎样实时猎取鼠标的目前坐标-
发布时间:08/01 来源:未知 浏览:
关键词:
一、事件的兼容:
function bindEvent(obj, event, fn) { if (obj.attachEvent) { //ie obj.attachEvent('on' + event, function () { fn.call(obj); }); } else { //chrome&ff obj.addEventListener(event, fn, false); } }
上面兼容ie8以及批改this关键字在ie低版本的指向,下面兼容chrome和ff。其他更常用的封装可以参照 我的javascript开源框架gdom
二、用立刻表达式搭建一个根本的库
增加猎取鼠标坐标的办法
;(function (window) { window.G = {}; function bindEvent(obj, event, fn) { if (obj.attachEvent) { //ie obj.attachEvent('on' + event, function () { fn.call(obj); }); } else { //chrome&ff obj.addEventListener(event, fn, false); } } G.getPos = function( dom ){ var oPos = { x : 0, y : 0 }; bindEvent( dom, 'mousemove', function( ev ){ var oEvent = ev || event, x, y; if ( oEvent.pageX || oEvent.pageY ){ x = oEvent.pageX; y = oEvent.pageY; }else { x = oEvent.clientX + document.body.scrollLeft || document.documentElement.scrollLeft; y = oEvent.clientX + document.body.scrollTop || document.documentElement.scrollTop; } x -= dom.offsetLeft; y -= dom.offsetTop; oPos.x = x; oPos.y = y; } ); return oPos; }; })(window);
三、引入封装的js库,绑定canvas为监听对象,打印目前鼠标的坐标
鼠标的坐标,我这里画了2根线,便于调查.
《script》 ;(function (window) { window.G = {}; function bindEvent(obj, event, fn) { if (obj.attachEvent) { //ie obj.attachEvent('on' + event, function () { fn.call(obj); }); } else { //chrome&ff obj.addEventListener(event, fn, false); } } G.getPos = function( dom ){ var oPos = { x : 0, y : 0 }; bindEvent( dom, 'mousemove', function( ev ){ var oEvent = ev || event, x, y; if ( oEvent.pageX || oEvent.pageY ){ x = oEvent.pageX; y = oEvent.pageY; }else { x = oEvent.clientX + document.body.scrollLeft || document.documentElement.scrollLeft; y = oEvent.clientX + document.body.scrollTop || document.documentElement.scrollTop; } x -= dom.offsetLeft; y -= dom.offsetTop; oPos.x = x; oPos.y = y; } ); return oPos; }; })(window); 《script》 《script》 window.onload = function(){ var oCanvas = document.querySelector( "#canvas" ), oGc = oCanvas.getContext( '2d' ), width = oCanvas.width, height = oCanvas.height, oInfo = document.querySelector( "#info" ), oPos = G.getPos( oCanvas ); oCanvas.addEventListener( "mousemove", function(){ oGc.clearRect( 0, 0, width, height ); oGc.beginPath(); oGc.moveTo( oPos.x, 0 ); oGc.lineTo( oPos.x, height ); oGc.moveTo( 0, oPos.y ); oGc.lineTo( width, oPos.y ); oGc.closePath(); oGc.strokeStyle = '#09f'; oGc.stroke(); oInfo.innerHTML = '鼠标的目前坐标是:(' + oPos.x + ',' + oPos.y + ')'; }, false ); } 《script》
以上就是怎样实时猎取鼠标的目前坐标 的细致内容,更多请关注 百分百源码网 其它相干文章!