program story

모바일 사파리 : 입력 필드의 Javascript focus () 메서드는 클릭으로 만 작동합니까?

inputbox 2020. 11. 21. 14:09
반응형

모바일 사파리 : 입력 필드의 Javascript focus () 메서드는 클릭으로 만 작동합니까?


이 문제에 대한 해결책을 찾을 수없는 것 같습니다.

이와 같은 간단한 입력 필드가 있습니다.

<div class="search">
   <input type="text" value="y u no work"/>
</div>​

그리고 focus()함수 내부에서 시도 하고 있습니다. 그래서 임의의 함수 안에 (그게 어떤 함수인지는 상관 없습니다)이 줄이 있습니다.

$('.search').find('input').focus();

이것은 모든 데스크탑에서 잘 작동합니다.

그러나 내 iPhone에서는 작동하지 않습니다. 필드에 초점이 맞춰지지 않고 키보드가 iPhone에 표시되지 않습니다.

테스트 목적과 문제를 보여주기 위해 간단한 샘플을 작성했습니다.

$('#some-test-element').click(function() {
  $('.search').find('input').focus(); // works well on my iPhone - Keyboard slides in
});

setTimeout(function() {
  //alert('test'); //works
  $('.search').find('input').focus(); // doesn't work on my iPhone - works on Desktop
}, 5000);​

focus()내 iPhone에서 시간 제한 기능이 작동하지 않는 이유를 알 수 있습니다.

라이브 예제를 보려면 iPhone에서이 바이올린을 테스트하십시오. http://jsfiddle.net/Hc4sT/

최신 정보:

현재 프로젝트에서 현재 직면하고있는 것과 똑같은 케이스를 만들었습니다.

"변경"할 때 포커스를 입력 필드로 설정하고 iphone 또는 기타 모바일 장치의 kexboard를 밀어 넣어야하는 선택 상자가 있습니다. focus ()가 올바르게 설정되었지만 키보드가 표시되지 않는다는 것을 알았습니다. 표시하려면 키보드가 필요합니다.

바로 여기에 테스트 파일을 업로드했습니다. http://cl.ly/1d210x1W3Y3W… 아이폰에서 테스트 해보면 키보드가 미끄러지지 않는 것을 알 수 있습니다.


사실, 여러분, 방법이 있습니다. http://forstartersapp.com (iPhone 또는 iPad에서 시도)에서 이것을 파악하기 위해 힘겹게 고생 했습니다.

기본적으로 터치 스크린 장치의 Safari는 focus()텍스트 상자에 대해 인색 합니다. 만약 당신이 그렇게한다면 일부 데스크탑 브라우저도 더 잘할 수 있습니다 click().focus(). 그러나 터치 스크린 기기의 Safari 디자이너는 키보드가 계속 올라 오면 사용자가 불편하다는 것을 깨달았 기 때문에 다음과 같은 조건에서만 초점을 맞추 었습니다.

1) 사용자가 어딘가를 클릭 focus()하고 클릭 이벤트를 실행하는 동안 호출되었습니다. AJAX 호출을 수행하는 경우 jQuery 의 더 이상 사용되지 않지만 여전히 사용 가능한 옵션 과 같이 동기식으로 수행 해야합니다$.ajax({async:false}) .

2) 게다가-그리고 이것은 잠시 동안 저를 바쁘게했습니다- focus()당시 다른 텍스트 상자에 초점이 맞춰져 있으면 여전히 작동하지 않는 것 같습니다. AJAX를 수행하는 "Go"버튼이 touchstart있어서 Go 버튼 이벤트에 대한 텍스트 상자를 흐리게 처리하려고했지만 키보드가 사라지고 Go 버튼을 클릭하기 전에 뷰포트를 이동했습니다. . 마지막으로 touchendGo 버튼 이벤트 에서 텍스트 상자를 흐리게 해 보았습니다 .

# 1과 # 2를 합치면 암호 필드에 포커스를 두어 로그인 양식을 모든 엉뚱한 웹 로그인 양식과 구별하여 더욱 기본적으로 느끼게하는 마법 같은 결과를 얻을 수 있습니다. 즐겨! :)


WunderBart의 답변에 대한 네이티브 자바 스크립트 구현.

글꼴 크기를 사용하여 자동 확대 / 축소 비활성화합니다 .

function onClick() {

  // create invisible dummy input to receive the focus first
  const fakeInput = document.createElement('input')
  fakeInput.setAttribute('type', 'text')
  fakeInput.style.position = 'absolute'
  fakeInput.style.opacity = 0
  fakeInput.style.height = 0
  fakeInput.style.fontSize = '16px' // disable auto zoom

  // you may need to append to another element depending on the browser's auto 
  // zoom/scroll behavior
  document.body.prepend(fakeInput)

  // focus so that subsequent async focus will work
  fakeInput.focus()

  setTimeout(() => {

    // now we can focus on the target input
    targetInput.focus()

    // cleanup
    fakeInput.remove()

  }, 1000)

}

나는 최근에 같은 문제에 직면했습니다. 모든 장치에서 작동하는 솔루션을 찾았습니다. 프로그래밍 방식으로 비동기 포커스를 수행 할 수 없지만 다른 입력에 이미 포커스가있을 때 포커스를 대상 입력으로 전환 할 수 있습니다 . 따라서해야 할 일은 DOM을 만들고 숨기고 추가하고 트리거 이벤트에 가짜 입력에 초점을 맞추고 비동기 작업이 완료되면 대상 입력에 초점을 다시 호출하는 것입니다. 다음은 스 니펫의 예입니다. 모바일에서 실행하세요.

편집하다:

다음 은 동일한 코드를 가진 바이올린입니다 . 분명히 당신은 모바일에서 첨부 된 스 니펫을 실행할 수 없습니다 (또는 제가 뭔가 잘못하고 있습니다).

var $triggerCheckbox = $("#trigger-checkbox");
var $targetInput = $("#target-input");

// Create fake & invisible input
var $fakeInput = $("<input type='text' />")
  .css({
    position: "absolute",
    width: $targetInput.outerWidth(), // zoom properly (iOS)
    height: 0, // hide cursor (font-size: 0 will zoom to quarks level) (iOS)
    opacity: 0, // make input transparent :]
  });

var delay = 2000; // That's crazy long, but good as an example

$triggerCheckbox.on("change", function(event) {
  // Disable input when unchecking trigger checkbox (presentational purpose)
  if (!event.target.checked) {
    return $targetInput
      .attr("disabled", true)
      .attr("placeholder", "I'm disabled");
  }

  // Prepend to target input container and focus fake input
  $fakeInput.prependTo("#container").focus();

  // Update placeholder (presentational purpose)
  $targetInput.attr("placeholder", "Wait for it...");

  // setTimeout, fetch or any async action will work
  setTimeout(function() {

    // Shift focus to target input
    $targetInput
      .attr("disabled", false)
      .attr("placeholder", "I'm alive!")
      .focus();

    // Remove fake input - no need to keep it in DOM
    $fakeInput.remove();
  }, delay);
});
label {
  display: block;
  margin-top: 20px;
}

input {
  box-sizing: border-box;
  font-size: inherit;
}

#container {
  position: relative;
}

#target-input {
  width: 250px;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container">
  <input type="text" id="target-input" placeholder="I'm disabled" />

  <label>
    <input type="checkbox" id="trigger-checkbox" />
    focus with setTimetout
   </label>
</div>


다음 코드로 작동하도록 관리했습니다.

event.preventDefault();
timeout(function () {
    $inputToFocus.focus();
}, 500);

I'm using AngularJS so I have created a directive which solved my problem:

Directive:

angular.module('directivesModule').directive('focusOnClear', [
    '$timeout',
    function (timeout) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var id = attrs.focusOnClear;
                var $inputSearchElement = $(element).parent().find('#' + id);
                element.on('click', function (event) {
                    event.preventDefault();
                    timeout(function () {
                        $inputSearchElement.focus();
                    }, 500);
                });
            }
        };
    }
]);

How to use the directive:

<div>
    <input type="search" id="search">
    <i class="icon-clear" ng-click="clearSearchTerm()" focus-on-clear="search"></i>
</div>

It looks like you are using jQuery, so I don't know if the directive is any help.


I have a search form with an icon that clears the text when clicked. However, the problem (on mobile & tablets) was that the keyboard would collapse/hide, as the click event removed focus was removed from the input.

text search input with close icon

Goal: after clearing the search form (clicking/tapping on x-icon) keep the keyboard visible!

To accomplish this, apply stopPropagation() on the event like so:

function clear ($event) {
    $event.preventDefault();
    $event.stopPropagation();
    self.query = '';
    $timeout(function () {
        document.getElementById('sidebar-search').focus();
    }, 1);
}

And the HTML form:

<form ng-controller="SearchController as search"
    ng-submit="search.submit($event)">
        <input type="search" id="sidebar-search" 
            ng-model="search.query">
                <span class="glyphicon glyphicon-remove-circle"
                    ng-click="search.clear($event)">
                </span>
</form>

This solution works well, I tested on my phone:

document.body.ontouchend = function() { document.querySelector('[name="name"]').focus(); };

enjoy


UPDATE

I also tried this, but to no avail:

$(document).ready(function() {
$('body :not(.wr-dropdown)').bind("click", function(e) {
    $('.test').focus();
})
$('.wr-dropdown').on('change', function(e) {
    if ($(".wr-dropdow option[value='/search']")) {
        setTimeout(function(e) {
            $('body :not(.wr-dropdown)').trigger("click");
        },3000)         
    } 
}); 

});

I am confused as to why you say this isn't working because your JSFiddle is working just fine, but here is my suggestion anyway...

Try this line of code in your SetTimeOut function on your click event:

document.myInput.focus();

myInput correlates to the name attribute of the input tag.

<input name="myInput">

And use this code to blur the field:

document.activeElement.blur();

Please try using on-tap instead of ng-click event. I had this issue. I resolved it by making my clear-search-box button inside search form label and replaced ng-click of clear-button by on-tap. It works fine now.

참고URL : https://stackoverflow.com/questions/12204571/mobile-safari-javascript-focus-method-on-inputfield-only-works-with-click

반응형