Javascript event.target 不适用于 Firefox
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7457260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
event.target not working on Firefox
提问by niko
var x = event.target||event.srcElement;
document.getElementById(x.id).style.left = 200 + "px" ;
document.getElementById(x.id).style.top = 100 + "px" ;
Works fine on google chrome and IE but not on firefox. Tried it on google. google says event.srcElement(works on IE but not on firefox) so i have added event.target but still not working. Is there anymore changes I need to do to work on firefox? By the way Im using 3.5 version of firefox.
在 google chrome 和 IE 上工作正常,但在 Firefox 上不工作。在谷歌上试过。谷歌说 event.srcElement(适用于 IE 但不适用于 firefox)所以我添加了 event.target 但仍然无法正常工作。在 Firefox 上工作我还需要做些什么改变吗?顺便说一下,我使用的是 3.5 版的 Firefox。
function up()
{
dragok = false;
document.onmousemove = null;
var x = event.target||event.srcElement;
document.getElementById(x.id).style.left= 200 + "px" ;
document.getElementById(x.id).style.top= 100 + "px" ;
}
Please help me to make it work on firefox
请帮我让它在 Firefox 上工作
回答by user113716
Make sure you define event
as a formal parameter to the handler.
确保您定义event
为处理程序的形式参数。
IE
defines it globally, and Chrome
defines it both in both places, so it works either way, but Firefox
only defines it as a function parameter.
IE
全局定义它,并Chrome
在两个地方都定义它,因此它可以以任何方式工作,但Firefox
仅将其定义为函数参数。
function up( e ) {
// ^-----------------------------------------------------+
if( !e ) e = window.event; // <---needed this --- and this ->--+
dragok = false;
document.onmousemove = null;
var x = e.target||e.srcElement; // <--- and these
document.getElementById(x.id).style.left= 200 + "px" ;
document.getElementById(x.id).style.top= 100 + "px" ;
}
回答by LipeTuga
I solved my problem using Jquery. For example to get the id of a element you can use:
我使用 Jquery 解决了我的问题。例如,要获取元素的 id,您可以使用:
var x = $(this).attr('id');
回答by balaji s
This solution to work in Firefox browser too. When start keydown
action then its set the event
property to global variable like this.
此解决方案也适用于 Firefox 浏览器。当开始keydown
动作时,它会event
像这样将属性设置为全局变量。
var keyEvent=null;
Assign that event
property to keyEvent
and .item
is target element.
该分配event
财产keyEvent
,并.item
为目标元素。
$(document).on("keydown",'.item', function(e){
keyEvent=e;
},this))
then.Use keyEvent
in your code.
然后。keyEvent
在您的代码中使用。
function up( e ) {
if( !e ) e = keyEvent;
dragok = false;
document.onmousemove = null;
var x = e.target||e.srcElement;
document.getElementById(x.id).style.left= 200 + "px" ;
document.getElementById(x.id).style.top= 100 + "px" ;
}
Note: Don't try to set the event
property to global variable of window
.
注意:不要尝试将event
属性设置为 的全局变量window
。