【问题标题】:How to make a button lose focus when page is loaded加载页面时如何使按钮失去焦点
【发布时间】:2013-10-03 09:14:37
【问题描述】:

当我的 JSP 页面被加载时,按钮(实际上是一个带有 onfocus 属性的图像按钮)获得焦点。所以,在按下回车键时,它会被点击。这是一个小问题,是更大问题的一部分。页面加载时如何让按钮失去焦点?

<html>
<head>
</head>
<body>
<div onkeypress =handleEnter()>
name <input  type="text" src='Create.gif' >
</br>
<input  type="image" src='Create.gif' onclick="alert('not done')">
<input  type="image" src='Create.gif' onclick="alert('done')">
</div>
</body>
<script>
function handleEnter()
{
if(window.event.keyCode==13)
{
alert('nothing');
event.cancelBubble=true;
}
}
</script>
</html>

提示框“无”和“未完成”均已显示

【问题讨论】:

  • 在这里发布您的代码..
  • 将焦点放在其他一些控件上,例如文本框等。
  • @theghostofc 怎么做?
  • 使用 $("#textfield").focus();正如@theghostofc 所说,将焦点转移到其他元素。
  • 你能告诉javascript吗

标签: javascript html javascript-events


【解决方案1】:

您可以使用autofocus HTML 属性 (specification reference) 在页面加载时自动聚焦不同的元素。我不确定这将如何应用于 JSP,但是在纯 HTML 中,这将类似于:

<button>My Button</button>
<button autofocus>My Other Button</button>

这是JSFiddle demo

【讨论】:

    【解决方案2】:

    我会修改这一行:

    <input  type="text" src='Create.gif' >
    

    <input  type="text" id="textbox" src='Create.gif' >
    <script>
    //$('#textbox').focus() //If your using jQuery
    document.getElementById('textbox').focus()
    </script>
    

    这会将焦点转移到文本框而不是图像按钮

    给你的文本框一个 id 并使用该 id 将焦点设置到该元素。

    document.getElementById('textbox').focus()
    

    【讨论】:

    • 你能告诉我javascritpt吗
    猜你喜欢
    • 2023-04-04
    • 2015-07-05
    • 1970-01-01
    • 2012-02-05
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多