2008年3月4日 星期二

Javascript Event 座標

節錄自
Javascript Event 座標

Javascript Event 的mouse座標用法
如果要得知 mouse畫面上的座標位置

function f(e) {
var e=(e)?e:event;
alert(e.clientY) ;
alert(e.clientX) ;
}

如果要得知 mouse頁面上的座標位置

function f(e) {
var e=(e)?e:event;
alert(e.clientY+document.documentElement.scrollTop) ;
alert(e.clientX+document.documentElement.scrollLeft) ;
}


該文章也參考了
Javascript's Event 的一点总结
這邊僅節錄部份內容

主要的差別在於html文件標頭是否有定義html的event事件
例:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>?定? HTML 的 Event 事件</title>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>定義了 HTML's DOCTYPE 的 Event 事件</title>


上述二種不一樣的html標籤,分別適用下述二種不一樣的javascript用法
這是未定義event事件的

<script language="javascript">
function getvalue(e){
if (!document.all){
winW = window.innerWidth;
winH = window.innerHeight;
curX = e.pageX - window.pageXOffset;
curY = e.pageY - window.pageYOffset;
mouX = e.pageX;
mouY = e.pageY;
broX = window.pageXOffset;
broY = window.pageYOffset;
}else{
winW = document.body.clientWidth;
winH = document.body.clientHeight;
curX = event.clientX;
curY = event.clientY;
mouX = event.clientX + document.body.scrollLeft;
mouY = event.clientY + document.body.scrollTop;
broX = document.body.scrollLeft;
broY = document.body.scrollTop;
}
alert(" 窗口可见宽度(winW): "+winW+"\n\n 窗口可见高度(winH): "+winH+"\n\n 距窗口左边距离(curX): "+curX+"\n\n 距窗口顶部距离(curY): "+curY+"\n\n 距页面左边距离(mouX): "+mouX+"\n\n 距页面顶部距离(mouY): "+mouY+"\n\n 页面滚动的宽度(broX): "+broX+"\n\n 页面滚动的高度(broY): "+broY);
return true;
}
document.onclick=getvalue;
</script>

然後,下面是有定義event事件的

<script language="JavaScript" type="text/javascript">
function getvalue(e){
if (!document.all){
winW = window.innerWidth;
winH = window.innerHeight;
curX = e.pageX - window.pageXOffset;
curY = e.pageY - window.pageYOffset;
mouX = e.pageX;
mouY = e.pageY;
broX = window.pageXOffset;
broY = window.pageYOffset;
}else{
winW = document.documentElement.clientWidth;
winH = document.documentElement.clientHeight;
curX = event.clientX;
curY = event.clientY;
mouX = event.clientX + document.documentElement.scrollLeft;
mouY = event.clientY + document.documentElement.scrollTop;
broX = document.documentElement.scrollLeft;
broY = document.documentElement.scrollTop;
}
alert(" 窗口可见宽度(winW): "+winW+"\n\n 窗口可见高度(winH): "+winH+"\n\n 距窗口左边距离(curX): "+curX+"\n\n 距窗口顶部距离(curY): "+curY+"\n\n 距页面左边距离(mouX): "+mouX+"\n\n 距页面顶部距离(mouY): "+mouY+"\n\n 页面滚动的宽度(broX): "+broX+"\n\n 页面滚动的高度(broY): "+broY);
return true;
}
document.onclick=getvalue;
</script>



可以看出最主要的差異在
document.body 變成了 document.documentElement

沒有留言: