onmousedown - 向左还是向右?
首先,我不是在寻找 jQuery 解决方案,只是在元素内部寻找简单的纯 Javascript 代码。
假设我们有以下 html 代码:
<select onmousedown=" ??? ">...</select>
我想要元素内部有一个简单的脚本来显示弹出消息 alert()
,其中包含按下了哪个按钮以及元素与文档的相对位置的信息 - 类似 jQuery 中的
offset()
。
First of all, I am not looking for jQuery solution, just simple pure Javascript code, inside of an element.
Let's say we have following html code:
<select onmousedown=" ??? ">...</select>
I want a simple script inside of the element to show popup message alert()
with information which button was pushed down and what is a relative position of the element to the document <body>
- something like offset()
in jQuery.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建一个具有某个名称的 JavaScript 函数,然后在
onmousedown
事件上调用它,传递可在函数内部使用的event
和this
对象。HTML
JS
如果您打算使用 jQuery,那么您可以使用此脚本
更新:
如果您想要内联脚本,请尝试此操作。
Create a JavaScript function with some name and then call it on
onmousedown
event passing theevent
andthis
object which can be used inside the function.HTML
JS
If you plan to use jQuery then you can use this script
Update:
If you want inline script then try this.
MouseEvent.button在不同浏览器中有不同的值
MouseEvent.button has different values in different browsers
编辑
<select id="foo" onmousedown="mouseDown()">...</select>
Edit
<select id="foo" onmousedown="function mouseDown(e){alert(MouseEvent.button + ' x:' + e.screenX + ' y:'+ e.screenY);}">...</select>
编辑
在继续之前,您可能想阅读这篇文章:Javascript 疯狂:鼠标事件
单击文档会发送 MouseEvent 对象 具有许多属性 - 例如 MouseEvent.button 告诉您按下了哪个鼠标按钮,MouseEvent.ctrlKey告诉您单击发生时是否按下了控制键。
请注意,这些按钮并不是真正的“左”和“右”,因为它们可以根据用户偏好进行更改,您想知道的是它是否是主按钮(通常是左按钮,但可能是右按钮,或者可能是完全不同的按钮)来自其他定点设备)或辅助按钮(通常是右侧的,但同样可以是任何东西)。
一些播放代码:
编辑
啊,到底是什么:
Edit
You might like to read this article before you go any further: Javascript Madness: Mouse Events
Clicks on a document dispatch a MouseEvent object that has lots of properties—e.g. MouseEvent.button tells you which mouse button was pressed, MouseEvent.ctrlKey tells you if the control key was pressed when the click occured.
Note that the buttons aren't really "left" and "right", since they can be changed by user preferences, what you want to know is whether it was the primary button (usually left but might be right or could be something totally different from some other pointing device) or the secondary button (usually right but again, could be anything).
Some play code:
Edit
Ah, what the hell: