在mac osx的firefox浏览器中.当点击按钮时,Activeelement返回body而不是button元素

In firefox browser of mac osx Document.activeelement returns body instead of button element on click of button

本文关键字:body 返回 Activeelement 元素 button 按钮 firefox osx mac 浏览器      更新时间:2023-09-26

在我的javascript上,我使用文档。activeelement来获取活动元素,但是对于按钮点击,它给我的是body而不是按钮在Mac OSX Yosemite的firefox浏览器中。

有谁能帮助我如何获得活动元素作为按钮。

示例代码

    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    function MainElement(){
    ActiveElement();}
    function ActiveElement()
    {
    var obj;
    obj=(window.event)?((event.target)?event.target:(event.srcElement)?event.srcElement:null):document.activeElement;
   alert(obj); // returns body element
    }
    </script>
    </head>
    <body>
    <button onclick="MainElement()"></button>
    </body>
    </html>

谢谢。

把你的HTML改成:

<button onclick="MainElement(event)">Button</button>

和JavaScript作为:

function MainElement(event) {
    ActiveElement(event);
}
function ActiveElement(event) {
    event = event || window.event
    alert (event.target); //The button HTMLElement
    alert (event.target.tagName); //BUTTON
}

一些注意事项:

  • 在IE中,事件对象完全通过显式对象window.event来访问。
  • 在Firefox中,通过传递一个事件参数到相关的事件处理函数来访问事件对象。