我想在数组中获得鼠标坐标。我也可以点击任何我无法进行鼠标坐标的地方。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<style>body {background-color: ivory;}</style>
</head>
<body>
<p id="results">result</p>
<script>
var x = document.getElementById("body");
var offsetX = x.offsetLeft;
var offsetY = x.offsetTop;
x.addEventListener('click', handleClick, false);
function handleClick(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
document.getElementById("results").innerHTML = "You clicked at: " + mouseX + "/" + mouseY;
}
</script>
</body>
</html>
答案 0 :(得分:2)
HTML中没有元素id="body"
。您可以使用<body>
访问document.body
元素。
此外,身体相当小,因为它只包含您的<p>
个元素,因此您可能需要添加一些css,以便您可以点击窗口中的任意位置并触发事件:
html, body {
height: 100%;
}
要将计算出的坐标存储在数组中,只需创建一个空白数组:
var coords = [];
然后为它们添加坐标:
coords.push([mouseX, mouseY]);
这是一个有效的例子:
var x = document.body;
var offsetX = x.offsetLeft;
var offsetY = x.offsetTop;
x.addEventListener('click', handleClick, false);
var coords = [];
function handleClick(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
coords.push([mouseX, mouseY]);
document.getElementById("results").innerHTML = "You have clicked at: " + JSON.stringify(coords);
}
&#13;
html, body {
height: 100%;
}
&#13;
<p id="results">result</p>
&#13;
答案 1 :(得分:2)
这就是我接近它的方式。
您没有ContextLoaderListener
id
的元素,因此我创建了一个ID为body
如果您想获得实际标签,则需要使用
bodyEquivalent
返回一个匹配元素数组(你可以从数组中获取第一个元素)
或更简单:getElementsByTagName('tag_name');
标记为document.body
body
&#13;
var x = document.getElementById("bodyEquivalent");
// or
// var x = document.body;
var offsetX = x.offsetLeft;
var offsetY = x.offsetTop;
x.addEventListener('click', handleClick, false);
// array to store click coords
var clickCoords = [];
// a point coord
var ClickPoint = function(x, y) {
this.x = x;
this.y = y;
};
ClickPoint.prototype.toString = function(){
return "(" + this.x + ", " + this.y + ")";
}
function handleClick(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// create click point and store it in array
var aClick = new ClickPoint(mouseX, mouseY);
clickCoords.push(aClick);
// update results
showArrayCoords(clickCoords);
}
function showArrayCoords(coords) {
var innerHtml = 'You clicked at:<br/>';
for (i = 0; i < coords.length; i++) {
innerHtml += coords[i] + "<br/>";
}
document.getElementById("results").innerHTML = innerHtml;
}
&#13;
#bodyEquivalent {
background-color: ivory;
border: 1px solid black;
width: 400px;
height: 300px;
}
&#13;