2012-10-12 51 views
2

我想檢測在id id clickdetectiondiv div我在哪裏點擊。我使用的代碼給了我相對於HTML頁面正文左上角的位置。我花了很多時間研究如何做到這一點,但無法找到答案。 我有一個解決方案是減去這個絕對定位的div的位置。但並不總是會得到div的位置,因爲屏幕尺寸可能會有所不同。請告訴我一個替代方法來做到這一點。如何檢測div中發生點擊事件的位置?

由於提前,

<html> 
<head> 
<script type="text/javascript"> 
function clicked(event){ 
    var x=event.clientX 
    var y=event.clientY 
    document.getElementById("outputdiv").innerHTML= "X coords: " + x + ", Y coords: " + y; 
} 
</script> 

<style type="text/css"> 
#clickdetectiondiv{ 
    position: absolute; 
    top: 100px; 
    left: 100px; 
    height: 100px; 
    width: 500px; 
    background: gray; 
} 
#outputdiv{ 
    position: absolute; 
    top: 300px; 
    left: 100px; 
    height: 100px; 
    width: 500px; 
    background: #eee; 
    text-align: center; 
} 
</style> 

</head> 

<body> 
<div id="clickdetectiondiv" onmousedown="clicked(event);"></div> 
<div id="outputdiv"></div> 
</body> 

</html> 
+0

嘗試http://stackoverflow.com/questions/442404/dynamically-retrieve-the-position- xy-of-html-element來確定div的位置,並從中得到子處理? – mariusnn

+0

這是關於畫布。我認爲div有類似的解決方案: http://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element – karaxuna

回答

0

你要使用像jQuery或mootools的一個JavaScript框架,他們有函數來獲取元素的相對位置,你想已經寫在一個跨瀏覽器的任何其他元素方式。爲什麼重新發明輪子?

0

如果你可以使用jQuery

$('#A').click(function(e) { //Default mouse Position 
       alert(e.pageX+ ' , ' + e.pageY); 
     }); 
0

我想這可能是解決方案:

function clicked(event){ 
    var x = event.x; 
    var y = event.y; 

    var divClicked = document.getElementById("clickdetectiondiv"); 

    x -= divClicked.offsetLeft; 
    y -= divClicked.offsetTop; 
    document.getElementById("outputdiv").innerHTML= "X coords: " + x + ", Y coords: " + y; 
} 
+0

http://help.dottoro.com/ljvbvmsj.php – mplungjan

+0

是的,這個正是我所需要的。非常感謝你.. – user1740795

相關問題