不使用按钮加载代码

Load code without using a button

我正在尝试更改此代码,以便它不再需要一个按钮来告诉我我正在使用哪个浏览器。我希望它在页面加载时弹出而不是在按钮上。如果有人可以向我展示所需的更改,那就太好了。

我尝试更改为 btn.onload 并添加 body onload="btn" 但这不起作用。

当前代码(带按钮):

<script type='text/javascript'>//<![CDATA[ 
  window.onload = function() {
    var btn = document.getElementById('btn');

    btn.onclick = function() {
      var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
      var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

      if (isChrome) alert("You are using Chrome!");
      if (isSafari) alert("You are using Safari!");
    };
  }//]]>  

</script>

</head>
<body>
<input type="button" style="cursor:pointer;" id="btn" name="btn" value="Detect browser!"/>

</body>

只需将 btn.onclick 替换为 window.onload

删除以下代码行:

btn.onclick = function() {
};
}//]]>  

这将导致所有包含的 javascript 在页面加载时执行。

您需要做的就是在加载 window 时 运行 它。

window.onload = function() {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

    if (isChrome) alert("You are using Chrome!");
    if (isSafari) alert("You are using Safari!");
};