[英]Why do I keep getting undefined when using clientx and clienty property?
var box=document.getElementById("box");
var display=document.getElementById("display");/*to display clientX result*/
var x=box.clientX;
box.addEventListener("click", show);
function show(){
display.innerHTML=x;
}
I feek like there is something simple going over my head that I just cant see 我觉得我的头脑里有一些简单的东西让我看不清楚
The properties are clientLeft
and clientTop
, not clientX
and clientY
. 属性是
clientLeft
和clientTop
,而不是clientX
和clientY
。 See the Element interface . 请参阅Element接口 。 So
所以
var x=box.clientLeft;
// -------------^^^^
Separately, and this may or may not be a problem depending on what you're doing, the line 另外,这可能是也可能不是问题,取决于你正在做什么,这条线
var x=box.clientX;
gets the value of clientX
from box
as of when it runs, and then stores that value . 从运行时的
box
获取clientX
的值 ,然后存储该值 。 There's no ongoing connection between x
and box.clientX
. x
和box.clientX
之间没有持续的连接。 So when the click occurs later and show
is called, it shows the value as of earlier , when var x=box.clientX;
因此,当点击后出现,并
show
被调用时,显示值如前所述 ,当var x=box.clientX;
ran. 跑了。 Depending on when that is, even if you make it
clientLeft
, you may get 0
instead of a valid value (if you're reading it during the initial loading of the page, and so the page may not have been laid out yet). 根据具体情况,即使您将其设置为
clientLeft
,也可能会获得0
而不是有效值(如果您在初始加载页面时正在读取它,那么页面可能尚未布局)。 Again, depending on what you're doing, you may want to wait and look up box.clientLeft
when the click occurs. 同样,根据您正在做的事情,您可能需要等待并在发生单击时查找
box.clientLeft
。 Eg: 例如:
var box = document.getElementById("box");
var display = document.getElementById("display");
box.addEventListener("click", show);
function show(){
display.innerHTML = box.clientLeft;
}
If you want to get the x-position of the mouse-click inside the box-element, you can achieve this with the help of the properties provided by the click-event. 如果要在box-element中获取鼠标单击的x位置,可以借助click-event提供的属性来实现此目的。
let box = document.getElementById("box");
let display = document.getElementById("display");
function showMouseX(event){
display.innerHTML = event.clientX;
}
box.addEventListener("click", showMouseX);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.