我想用Javascript实现,当页面加载完成后,让页面上的一个<input>自动获得焦点。并触发它的onfocus事件。
|
<body onload="document.getElementById('textbox1').focus();">
<input type="text" id="textbox1"/> 楼上的方法是一般方法。除此方法外还可以:一种是从后台代码向前台写Javascript,一种是直接在前台写上Javascript,具体方法如下: 第一种方法: 【后台CS页Page_Load事件代码】 using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack)//根据情况而定看是否需要此判断 { this.ClientScript.RegisterStartupScript(this.GetType(), "plok", "<script language='javascript' type='text/javascript'>okonfocus();</script>"); } } } 【前台页面脚本代码如下】 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Input测试页</title> <script language="javascript" type="text/javascript"> function okonfocus() { var myok = document.getElementById("OK"); myok.value = "OK已经获得了焦点,并执行了okonfocus()函数!"; myok.focus(); } </script> </head> <body> <form id="form1" runat="server"> <div> <input id="OK" type="text" onfocus="okonfocus();" style="width: 435px"/> </div> </form> </body> </html> 第二种方法: 【只有前台页面脚本代码如下】 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Input测试页</title> <script language="javascript" type="text/javascript"> function okonfocus() { var myok = document.getElementById("OK"); myok.value = "OK已经获得了焦点,并执行了okonfocus()函数!"; myok.focus(); } </script> </head> <body> <form id="form1" runat="server"> <div> <input id="OK" type="text" onfocus="okonfocus();" style="width: 435px"/> </div> <script language="javascript" type="text/javascript"> okonfocus(); </script> </form> </body> </html> window.onload = function() { ... } |