답변:
귀하의 질문에는 두 부분이 있습니다.
1) 페이지로드에 입력을 집중하는 방법은 무엇입니까?
autofocus입력에 속성을 추가하기 만하면 됩니다.
<input id="myinputbox" type="text" autofocus>
그러나 이것은 모든 브라우저에서 지원되지 않을 수 있으므로 javascript를 사용할 수 있습니다.
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) 입력 텍스트 끝에 커서를 놓는 방법은 무엇입니까?
다음은 다른 SO 답변 에서 빌린 코드가 포함 된 비 jQuery 솔루션입니다 .
function placeCursorAtEnd() {
if (this.setSelectionRange) {
// Double the length because Opera is inconsistent about
// whether a carriage return is one character or two.
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
// This might work for browsers without setSelectionRange support.
this.value = this.value;
}
if (this.nodeName === "TEXTAREA") {
// This will scroll a textarea to the bottom if needed
this.scrollTop = 999999;
}
};
window.onload = function() {
var input = document.getElementById("myinputbox");
if (obj.addEventListener) {
obj.addEventListener("focus", placeCursorAtEnd, false);
} else if (obj.attachEvent) {
obj.attachEvent('onfocus', placeCursorAtEnd);
}
input.focus();
}
다음은 jQuery로이 작업을 수행하는 방법의 예입니다.
<input type="text" autofocus>
<script>
$(function() {
$("[autofocus]").on("focus", function() {
if (this.setSelectionRange) {
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
this.value = this.value;
}
this.scrollTop = 999999;
}).focus();
});
</script>
주의 사항-이제이를 지원하는 브라우저의 경우 JavaScript없이 HTML5로이 작업을 수행 할 수 있습니다.
<input type="text" autofocus>
아마도 이것으로 시작하여 JavaScript로 빌드하여 이전 브라우저에 대한 대체를 제공 할 수 있습니다.
$(document).ready(function() {
$('#id').focus();
});
이를 수행하는 이식 가능한 방법은 이와 같은 사용자 정의 함수 (브라우저 차이를 처리하기 위해)를 사용하는 것 입니다.
그런 다음 jessegavin이 쓴 것처럼 태그 onload끝에 대한 핸들러를 설정합니다 <body>.
window.onload = function() {
document.getElementById("myinputbox").focus();
}
이것은 나를 위해 잘 작동하는 것입니다.
<form name="f" action="/search">
<input name="q" onfocus="fff=1" />
</form>
fff는 이름이 절대적으로 무관 한 전역 변수이며 해당 입력에 초점을 맞추기 위해 일반 onload 이벤트를 중지하는 것을 목표로합니다.
<body onload="if(!this.fff)document.f.q.focus();">
<!-- ... the rest of the page ... -->
</body>
에서 : http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html