gpt4 book ai didi

javascript - 如何通过 JavaScript 检测事件?

转载 作者:行者123 更新时间:2023-12-02 18:15:23 28 4
gpt4 key购买 nike

我必须提交文件。一个 HTML:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>JavaScriptSolution</title>
<script src='./script.js' charset='utf-8' defer='defer'></script>
</head>
<body>
<input id='A1' value='On Keydown' style='width:100px; height:50px; margin:30px;'/>

<input id='A2' value='On Keyress' style='width:100px; height:50px; margin:30px;'/>

<input id='A3' value='On Keyup' style='width:100px; height:50px; margin:30px;'/>

<input id='A4' value='On Focus' style='width:100px; height:50px; margin:30px;'/>

<input id='A5' value='On Blur' style='width:100px; height:50px; margin:30px;'/>

<div id='A6' style='width:100px; height:50px; margin:30px;'>
On Click
</div>
<div id='A7' style='width:100px; height:50px; margin:30px;'>
On Mouse Move
</div>
<div id='A8' style='width:100px; height:50px; margin:30px;'>
On Mouse Over
</div>
<div id='A9' style='width:100px; height:50px; margin:30px;'>
On Mouse Out
</div>


</body>
</html>

还有另一种 JavaScript:

function byid(id_name) 
{
return document.getElementById(id_name);
}

byid('A1').onkeydown=function a1(){ alert('On Keydown'); }
byid('A2').onkeypress=function a2(){ alert('On Keypress') ; }
byid('A3').onkeyup=function a3(){ alert('On Keyup') ; }
byid('A4').onfocus=function a4(){ alert('On Focus'); }
byid('A5').onblur=function a5(){ alert('On Blur') ; }
byid('A6').onclick=function a6(){ alert('On Click') ; }
byid('A7').onmousemove=function a7(){ alert('On Mouse Move') ; }
byid('A8').onmouseover=function a8(){ alert('On Mouse Over') ; }
byid('A9').onmouseout=function a9(){ alert('On Mouse Out') ; }

我的脚本在 Firefox、Safari、IE、Chrome 上运行良好。但不适用于 Opera 和一些 Android 浏览器。我的脚本出了什么问题?

谁能解决这个问题吗?

最佳答案

添加defer='defer'脚本标签确实应该等到页面完全加载,但就目前情况而言,即使现在并不是所有浏览器都支持它,即它们会忽略它,导致执行代码时元素不存在。

浏览器支持的完整列表可见here 。快照:

您可能使用的是旧版本的 Opera 或 Opera mini,因此它不起作用。

要解决这个问题,只需使用非常基本的 window.onload 即可安全起见适用于所有浏览器:

window.onload = function() {
byid('A1').onkeydown=function a1(){ alert('On Keydown'); }
byid('A2').onkeypress=function a2(){ alert('On Keypress') ; }
//...
};

另一种方法是将带有 JS 文件引用的脚本标记放置在文档的最后,就在 </body> 之前。标签 - 有或没有defer .

关于javascript - 如何通过 JavaScript 检测事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19345340/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com