웹 페이지가로드 될 때 포커스를 텍스트 상자로 자동 설정하는 방법은 무엇입니까?
웹 페이지가로드 될 때 포커스를 텍스트 상자로 자동 설정하는 방법은 무엇입니까?
HTML 태그가 있거나 Javascript를 통해 수행해야합니까?
jquery를 사용하는 경우 :
$(function() {
$("#Box1").focus();
});
또는 프로토 타입 :
Event.observe(window, 'load', function() {
$("Box1").focus();
});
또는 일반 자바 스크립트 :
window.onload = function() {
document.getElementById("Box1").focus();
};
그러나 이것은 다른로드 핸들러를 대체한다는 점을 명심하십시오 .Google에서 addLoadEvent ()를 찾아서 교체하지 않고 onload 핸들러를 추가하는 안전한 방법을 찾으십시오.
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>
JS가 HTML 요소 아래에 있으므로 jQuery, onload 또는 이벤트 핸들러가 필요하지 않습니다.
편집 : 또 다른 장점은 일부 브라우저에서 JavaScript를 끈 상태로 작동하며 이전 브라우저를 지원하지 않으려는 경우 JavaScript를 제거 할 수 있다는 것입니다.
편집 2 : Firefox 4는 이제 autofocus
속성을 지원하므로 IE는 지원하지 않습니다.
자바 스크립트를 사용해야합니다.
<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를 호출하고 원하는 텍스트 상자에 포커스를 설정하는 함수를 참조하십시오.
텍스트 필드에 자동 초점을 작성하십시오. 이것은 간단하며 다음과 같이 작동합니다.
<input name="abc" autofocus></input>
도움이 되었기를 바랍니다.
일반 바닐라 HTML 및 자바 스크립트 사용
<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>
For those out there using the .net framework and asp.net 2.0 or above, its trivial. If you are using older versions of the framework, you'd need to write some javascript similar to above.
In your OnLoad handler (generally page_load if you are using the stock page template supplied with visual studio) you can use:
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
(* Note I removed the underscore character from the function name that is generally Page_Load since in a code block it refused to render properly! I could not see in the markup documentation how to get underscores to render unescaped.)
Hope this helps.
You can do it easily by using jquery in this way:
<script type="text/javascript">
$(document).ready(function () {
$("#myTextBoxId").focus();
});
</script>
by calling this function in $(document).ready()
.
It means this function will execute when the DOM is ready.
For more information about the READY function, refer to : http://api.jquery.com/ready/
<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>
IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:
$(document).ready(function() {
$('input:text[value=""]:visible:enabled:first').focus();
});
Hope that helps...
Thanks...
As a general advice, I would recommend not stealing the focus from the address bar. (Jeff already talked about that.)
Web page can take some time to load, which means that your focus change can occur some long time after the user typed the pae URL. Then he could have changed his mind and be back to url typing while you will be loading your page and stealing the focus to put it in your textbox.
That's the one and only reason that made me remove Google as my start page.
Of course, if you control the network (local network) or if the focus change is to solve an important usability issue, forget all I just said :)
I had a slightly different problem. I wanted autofocus
, but, wanted the placeholder
text to remain, cross-browser. Some browsers would hide the placeholder
text as soon as the field focused, some would keep it. I had to either get placeholders staying cross-browser, which has weird side effects, or stop using autofocus
.
So I listened for the first key typed against the body tag, and redirected that key into the target input field. Then all the event handlers involved get killed off to keep things clean.
var urlInput = $('#Url');
function bodyFirstKey(ev) {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
if (ev.target == document.body) {
urlInput.focus();
if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {
urlInput.val(ev.key);
return false;
}
}
};
function urlInputFirstFocus() {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
};
$('body').keydown(bodyFirstKey);
urlInput.focus(urlInputFirstFocus);
https://jsfiddle.net/b9chris/qLrrb93w/
If you are using ASP.NET then you can use
yourControlName.Focus()
in the code on the server, which will add appropriate JavaScript into the page.
Other server-side frameworks may have an equivalent method.
Use the below code. For me it is working
jQuery("[id$='hfSpecialty_ids']").focus()
'Programming' 카테고리의 다른 글
HttpListener 액세스가 거부되었습니다. (0) | 2020.06.04 |
---|---|
“Thread.sleep”이없는“while (true)”가 Linux에서 100 % CPU 사용을 야기하지만 Windows에서는 왜 발생하지 않습니까? (0) | 2020.06.04 |
with 문에서 사용되는 open을 어떻게 조롱합니까 (Python에서 Mock 프레임 워크 사용)? (0) | 2020.06.04 |
SQL Server에 대한 LIMIT 및 OFFSET에 해당합니까? (0) | 2020.06.04 |
Swift에서 NSDocumentDirectory를 찾는 방법은 무엇입니까? (0) | 2020.06.04 |