javascript - 通过指定坐标检索html控件 [英] javascript - retrieving html control by specifying coordinates

查看:52
本文介绍了javascript - 通过指定坐标检索html控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过指定触发事件的坐标(如onmousedown,onmouseup,onclick等等)来获取html控件的id。坐标可以通过

how can i get the id of a html control just by specifying the coordinates of a triggered event (like onmousedown, onmouseup, onclick, etc..). the coordinates can be got by

e.clientX,e.clientY获得,其中e是事件对象。

e.clientX , e.clientY where e is the event object.

我们的想法是获得一个控件的id,在该控件上完成click事件而不在该控件的定义中有任何onClick事件。

the idea is to get the id of control on which a click event is done without having any onClick event in that control's definition.

这样就无需为多个控件指定onClick事件。

this will dispense the need of specifying the onClick event for multiple controls.

推荐答案

我不相信这是可能的,但幸运的是(如果我理解你的要求正确)你不需要:

I do not believe that this is possible, but fortunately (if I understand your requirements correctly) you do not need to:

如果你想获得用户单击的HTML元素,而不在每个元素上指定单击事件处理程序,只需在顶级元素上指定一个单击处理程序(一个包含所有其他有趣元素的元素 - 甚至可能是document),然后查看MouseEvent的target属性 - 它将指定最初接收点击的HTML元素,而不是指定onclick事件处理程序的元素(这可以通过使用this关键字来获得)。

If you want to get the HTML element where a user clicked, without specifying a click event handler on each element, simply specify a click handler on a top level element (one that contains all the other interesting elements - maybe even "document"), and then look at the MouseEvent's target property - it will specify the HTML element that received the click initially and not the element where you specified the onclick event handler (this can be gotten to simply by using the "this" keyword).

如果你有firebug,请在你的firebug控制台上试试这个:StackOverflow:

If you have firebug, try this out in your firebug console right here on StackOverflow:

document.getElementById('question').onclick = function(e) { 
  var target = window.event?window.event.srcElement:e.target; 
  alert("Got click: " + target); 
}

然后点击问题文本的任意位置以获取包含正确HTML元素的提醒:-)。

Then click anywhere on your question text to get an alert with the correct HTML element :-) .

这篇关于javascript - 通过指定坐标检索html控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆