网页加载后如何自动将焦点设置到文本框?

时间:2020-03-05 18:48:13  来源:igfitidea点击:

网页加载后如何自动将焦点设置到文本框?

是否有HTML标记可以执行此操作,还是必须通过Javascript完成?

解决方案

回答

我们需要使用javascript:

<BODY onLoad="document.getElementById('myButton').focus();">

@Ben指出,我们不应添加这样的事件处理程序。虽然这是另一个问题,但他建议我们使用此功能:

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

然后在页面上调用addLoadEvent并引用一个将焦点设置到所需文本框的函数。

回答

<html>  
<head>  
<script language="javascript" type="text/javascript">  
function SetFocus(InputID)  
{  
   document.getElementById(InputID).focus();  
}  
</script>  
</head>  
<body onload="SetFocus('Box2')">  
<input id="Box1" size="30" /><br/>  
<input id="Box2" size="30" />  
</body>  
</html>

回答

如果我们使用的是jquery:

$(function() {
  $("#Box1").focus();
});

或者原型:

Event.observe(window, 'load', function() {
  $("Box1").focus();
});

还是普通的javascript:

window.onload = function() {
  document.getElementById("Box1").focus();
};

尽管请记住,这将替换其他加载处理程序,所以请在Google中查找addLoadEvent()以获取添加加载处理程序而不是替换的安全方法。

回答

使用普通的html和javascript

<input type='text' id='txtMyInputBox' />

<script language='javascript' type='text/javascript'>
function SetFocus()
{
    // safety check, make sure its a post 1999 browser
    if (!document.getElementById)
    {
        return;
    }

    var txtMyInputBoxElement = document.getElementById("txtMyInputBox");

    if (txtMyInputBoxElement != null)
    {
        txtMyInputBoxElement.focus();
    }
}
SetFocus();
</script>

对于那些使用.net框架和asp.net 2.0或者更高版本的用户而言,它是微不足道的。如果我们使用的是较早版本的框架,则需要编写一些与上述类似的javascript。

在OnLoad处理程序中(如果使用的是Visual Studio提供的股票页面模板,通常为page_load),我们可以使用:

C#

protected void PageLoad(object sender, EventArgs e)
{
    Page.SetFocus(txtMyInputBox);
}

VB.NET

Protected Sub PageLoad(sender as Object, e as EventArgs)

    Page.SetFocus(txtMyInputBox)

End Sub

(*请注意,我从通常是Page_Load的函数名中删除了下划线字符,因为在代码块中它拒绝正确渲染!我在标记文档中看不到如何使下划线呈现为未转义。)

希望这可以帮助。

回答

作为一般建议,我建议不要从地址栏中窃取焦点。 (杰夫已经谈论过了。)

加载网页可能需要一些时间,这意味着在用户键入Pae URL之后很长时间就会发生焦点更改。然后,他可能会改变主意,而在我们将要加载页面并窃取焦点以将其放入文本框时又返回到url输入。

这就是让我删除Google作为起始页的唯一原因。

当然,如果我们控制网络(本地网络),或者如果重点是解决重要的可用性问题,请忘记我刚才所说的所有内容:)

回答

在HTML中,所有表单字段都有一个" autofocus"属性。 Dive Into HTML 5中有一个很好的教程。不幸的是,当前版本低于10的IE版本不支持该教程。

要使用HTML 5属性并使用JS选项,请执行以下操作:

<input id="my-input" autofocus="autofocus" />
<script>
  if (!("autofocus" in document.createElement("input"))) {
    document.getElementById("my-input").focus();
  }
</script>

不需要jQuery,onload或者事件处理程序,因为JS位于HTML元素下方。

编辑:另一个优点是,它在某些浏览器中可以关闭JavaScript,并且当我们不希望支持较旧的浏览器时可以删除JavaScript。

编辑2:Firefox 4现在支持autofocus属性,只是不支持IE。

回答

恕我直言,选择页面上第一个可见的,启用的文本字段的"最干净"方法是使用jQuery并执行以下操作:

$(document).ready(function() {
  $('input:text[value=""]:visible:enabled:first').focus();
});

希望对我们有帮助...

谢谢...