如何在页面中添加焦点 JavaScript实例
细心的朋友不难发现,人性化的网站都是进行过焦点处理的。即可以通过回车键来完成确定或提交功能。
而通常情况下,默认按钮是没有焦点的,这就需要我们通过一些方法把焦点加上。下面就简单介绍一下Js添加
焦点的方法。
/// <summary>
/// 添加焦点
/// </summary>
private void Script()
{
//实例化一个StringBuilder实例
StringBuilder sb = new StringBuilder();
//找到页面中的各个控件
Button btnOK = this.FindControl("btn_AddSec") as Button;
TextBox txtcode = this.FindControl("txt_SchoolCode") as TextBox;
TextBox txtname = this.FindControl("txt_SchoolName") as TextBox;
TextBox txtsec = this.FindControl("txt_TotalNum") as TextBox;
//添加JS函数
sb.Append("function f()\n{\n");
sb.Append("var finishbtn;\n");
sb.Append("finishbtn = document.getElementById('" + btnOK.ClientID + "');\n");
sb.Append("if(event.keyCode=='13')\n{\n");
sb.Append("if(finishbtn!=undefined){\n");
sb.Append("finishbtn.click();\n");
sb.Append("return false;\n");
sb.Append("}\n");
sb.Append("}\n");
sb.Append("}\n");
//将相应控件的属性加上此函数
txtcode.Attributes["onkeypress"] = "return f();";
txtname.Attributes["onkeypress"] = "return f();";
txtsec.Attributes["onkeypress"] = "return f();";
//注册
Page.ClientScript.RegisterClientScriptBlock(typeof(string), Guid.NewGuid().ToString(), sb.ToString(), true);
}
/// 添加焦点
/// </summary>
private void Script()
{
//实例化一个StringBuilder实例
StringBuilder sb = new StringBuilder();
//找到页面中的各个控件
Button btnOK = this.FindControl("btn_AddSec") as Button;
TextBox txtcode = this.FindControl("txt_SchoolCode") as TextBox;
TextBox txtname = this.FindControl("txt_SchoolName") as TextBox;
TextBox txtsec = this.FindControl("txt_TotalNum") as TextBox;
//添加JS函数
sb.Append("function f()\n{\n");
sb.Append("var finishbtn;\n");
sb.Append("finishbtn = document.getElementById('" + btnOK.ClientID + "');\n");
sb.Append("if(event.keyCode=='13')\n{\n");
sb.Append("if(finishbtn!=undefined){\n");
sb.Append("finishbtn.click();\n");
sb.Append("return false;\n");
sb.Append("}\n");
sb.Append("}\n");
sb.Append("}\n");
//将相应控件的属性加上此函数
txtcode.Attributes["onkeypress"] = "return f();";
txtname.Attributes["onkeypress"] = "return f();";
txtsec.Attributes["onkeypress"] = "return f();";
//注册
Page.ClientScript.RegisterClientScriptBlock(typeof(string), Guid.NewGuid().ToString(), sb.ToString(), true);
}
然后只需要在相应的地方调用就可以了。