로드시 포커스 입력 상자


95

페이지로드시 커서가 특정 입력 상자에 어떻게 초점을 맞출 수 있습니까?

초기 텍스트 값도 유지하고 입력 끝에 커서를 놓을 수 있습니까?

<input type="text"  size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />

답변:


170

귀하의 질문에는 두 부분이 있습니다.

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>

3
제안 된 첫 번째 코드 블록은 실제로 커서를 기존 값의 끝에 배치합니다. 잘 작동합니다. 당신의 도움에 감사드립니다.
Codex73 2010

46

주의 사항-이제이를 지원하는 브라우저의 경우 JavaScript없이 HTML5로이 작업을 수행 할 수 있습니다.

<input type="text" autofocus>

아마도 이것으로 시작하여 JavaScript로 빌드하여 이전 브라우저에 대한 대체를 제공 할 수 있습니다.


알아서 반갑습니다. 이미 커서가 입력 필드의 마지막 위치로 이동합니까?
Camilo Díaz Repka

1
@ Codex73이 HTML5의 자리 표시 자 속성이 수행하는 작업을 수행하려고한다고 생각하지 않습니다. 현재 입력에있는 값의 끝에 커서가 자동으로 배치되기를 원하는 것처럼 들립니다.
jessegavin 2010

2
당신 말이 맞습니다. 이것은 완전한 해결책이 아닙니다. 그러나 이것은 몇 가지 문제를 해결합니다 (onload autofocus 및 placeholder 텍스트).
David Calhoun

2019 년
sporker


3
function focusOnMyInputBox(){                                 
    document.getElementById("myinputbox").focus();
}

<body onLoad="focusOnMyInputBox();">

<input type="text"  size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text">

2

이를 수행하는 이식 가능한 방법은 이와 같은 사용자 정의 함수 (브라우저 차이를 처리하기 위해)를 사용하는 입니다.

그런 다음 jessegavin이 쓴 것처럼 태그 onload끝에 대한 핸들러를 설정합니다 <body>.

window.onload = function() {
  document.getElementById("myinputbox").focus();
}


1

매우 간단한 한 줄 솔루션 :

<body onLoad="document.getElementById('myinputbox').focus();">

0

이것은 나를 위해 잘 작동하는 것입니다.

<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


0

어떤 이유로 BODY 태그에 추가 할 수없는 경우 양식 다음에 추가 할 수 있습니다.

<SCRIPT type="text/javascript">
    document.yourFormName.yourFieldName.focus();
</SCRIPT>

0

시험:

Javascript Pure :

[elem][n].style.visibility='visible';
[elem][n].focus();

Jquery :

[elem].filter(':visible').focus();

0

이것을 js 상단에 추가하십시오.

var input = $('#myinputbox');

input.focus();

또는 html로

<script>
    var input = $('#myinputbox');

    input.focus();
</script>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.