让控件获取焦点及设置输入法全角半角或无效
做开发的过程中,常遇到一些页面要求光标的默认位置固定在某控件上
看起来好像很难,其实实现方法很简单.
JavaScript里面有现成的设置焦点的方法
可以写一个简单的函数命名为setFocus,然后在Page_Load里调用就可以了
比如需要设置焦点的是mytextbox控件
那么只要Page_Load写上Call setFocus(Me.mytextbox)就可以了
下面是VB.NET代码实例.C#的代码也差不多...
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call setFocus(Me.txt_code)
End Sub
Private Sub setFocus(ByVal ctrl As Control)
Dim script As String
script = "<script language='JavaScript'>" & _
" document.getElementById('" & ctrl.ClientID & "').focus();" & _
"</script>"
RegisterStartupScript("setfocus", script)
End Sub
下面是输入法设置,更简单:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
'IME半角設定
setIME(Me.Page, Me.txt_code, 1)
setIME(Me.Page, Me.txt_date, 1)
End If
End Sub
Public Sub setIME(ByRef pgTemp As Page, _
ByRef ctrTemp As WebControl, _
ByVal intMode As Integer)
Select Case intMode
Case 0 'IME無効
ctrTemp.Attributes.Add("style", "ime-mode:disabled")
Case 1 'IME半角
ctrTemp.Attributes.Add("style", "ime-mode:inactive")
Case 2 'IME全角
ctrTemp.Attributes.Add("style", "ime-mode:active")
Case 3 'IME自動
ctrTemp.Attributes.Add("style", "ime-mode:auto")
Case 4 'IME無効且右对齐
ctrTemp.Attributes.Add("style", "ime-mode:disabled;text-align:right")
Case 5 'IME半角且右对齐
ctrTemp.Attributes.Add("style", "ime-mode:inactive;text-align:right")
End Select
End Sub