모바일 사파리 : 입력 필드의 자바스크립트 포커스() 메소드는 클릭에서만 작동합니까?
저는 이런 간단한 입력란이 있습니다.
<div class="search">
<input type="text" value="y u no work"/>
</div>
하려고 focus()
함수 안에 있는 거죠 의 함수에는 이따라서 임의 함수 안에는 이 선이 있습니다.
$('.search').find('input').focus();
이것은 모든 데스크탑에서 잘 작동합니다.
하지만 제 아이폰에서는 작동이 되지 않습니다.필드가 초점이 맞지 않고 키보드가 아이폰에 표시되지 않습니다.
테스트 목적으로 그리고 여러분께 문제를 보여드리기 위해 저는 간단한 샘플을 만들었습니다.
$('#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에서 이 fiddle을 테스트해 보십시오.http://jsfiddle.net/Hc4sT/
업데이트:
현재 진행 중인 프로젝트와 똑같은 케이스를 만들었습니다.
저는 선택 상자를 가지고 있는데, 이 상자는 "변경"되면 초점을 입력 필드에 맞추고 아이폰이나 다른 모바일 기기의 멕스 보드에 끼워 넣어야 합니다.포커스()가 올바르게 설정되어 있는데 키보드가 표시되지 않는 것을 발견했습니다.키보드가 있어야 나타나요.
사실, 여러분, 방법이 있습니다.저는 [LINK Removed](아이폰이나 아이패드에서 사용해 보세요)를 위해 이를 파악하기 위해 힘겹게 노력했습니다.
합니다에 는 인색합니다.focus()
텍스트 상자 일부 데스크톱 브라우저도 더 잘합니다를 브라우저도 더 .click().focus()
해서 뜨면 것을 때문에과 같은 조건에서만 하지만 터치스크린 장치의 Safari 설계자들은 키보드가 계속해서 뜨면 사용자들에게 짜증이 난다는 것을 알았기 때문에 초점이 다음과 같은 조건에서만 보이도록 했습니다.
하고 1) ,focus()
클릭 이벤트를 실행하는 동안 호출되었습니다.AJAX 호출을 수행하는 경우 사용하지 않는 것과 같이 동기화해야 합니다(단, 사용 가능).$.ajax({async:false})
j의 의 옵션 쿼리.
그리고 이 2) , .focus()
다른 텍스트 상자에 초점이 맞춰진 경우에도 여전히 작동하지 않는 것으로 보입니다. "이 있어서했습니다 AJAX는 "Go"서의 를 흐리게 해 .는.touchstart
이동 버튼의 이벤트, 하지만 그것은 키보드를 사라지게 만들었고 내가 이동 버튼 클릭을 완료하기 전에 뷰포트를 옮겼습니다. 만들어 .touchend
Go 버튼 이벤트, 정말 매력적으로 잘 풀렸어요!
#1과 #2를 합하면 비밀번호 필드에 초점을 맞춰 로그인 양식을 모든 엉망인 웹 로그인 양식과 다르게 설정하고 보다 네이티브한 느낌을 줄 수 있는 마법의 결과를 얻을 수 있습니다.맛있게 드세요.:)
분더바트의 답변을 네이티브 자바스크립트로 구현한 것입니다.
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)
}
기타 참고문헌:자동 확대/축소 비활성화 입력 "텍스트" 태그 - iPhone의 Safari
저는 최근에 같은 문제에 직면했습니다.모든 기기에 효과가 있는 솔루션을 찾았습니다.비동기 포커스를 프로그래밍 방식으로 수행할 수는 없지만 다른 입력이 이미 포커스를 맞추고 있을 때 포커스를 목표 입력으로 전환할 수 있습니다.따라서 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>
이 솔루션은 잘 작동합니다. 휴대폰으로 테스트해 봤습니다.
document.body.ontouchend = function() { document.querySelector('[name="name"]').focus(); };
즐거운 시간 되세요.
클릭하면 텍스트가 지워지는 아이콘이 있는 검색 양식이 있습니다. 및 괴에서)다는에 이었습니다.click
dfocus
되었습니다에서 input
.
목표: 검색양식을 지운 후(x아이콘 클릭/탭) 키보드가 보이게 유지!
이 작업을 수행하려면 신청하십시오.stopPropagation()
에:
function clear ($event) {
$event.preventDefault();
$event.stopPropagation();
self.query = '';
$timeout(function () {
document.getElementById('sidebar-search').focus();
}, 1);
}
그리고 HTML 양식:
<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>
저는 다음 코드를 사용하여 성공적으로 작동할 수 있었습니다.
event.preventDefault();
timeout(function () {
$inputToFocus.focus();
}, 500);
앵귤러를 쓰고 있습니다.JS를 사용하여 제 문제를 해결하는 지침을 만들었습니다.
지시:
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);
});
}
};
}
]);
지시어 사용 방법:
<div>
<input type="search" id="search">
<i class="icon-clear" ng-click="clearSearchTerm()" focus-on-clear="search"></i>
</div>
jQuery를 사용하시는 것 같은데 지시사항이 도움이 되는지 모르겠네요.
갱신하다
나도 이것을 시도해 보았지만 소용이 없었습니다.
$(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)
}
});
});
당신의 JSFiddle이 정상적으로 작동하지 않기 때문에 당신이 왜 이것이 작동하지 않는다고 말하는지 헷갈리지만, 어쨌든 여기 제 제안이 있습니다.
클릭 이벤트에서 SetTimeOut 기능에서 다음 코드 라인을 시도해 보십시오.
document.myInput.focus();
myInput은 입력 태그의 이름 속성과 관련이 있습니다.
<input name="myInput">
그리고 이 코드를 사용하여 필드를 흐리게 합니다.
document.activeElement.blur();
시도해 보기:
input.focus();
input.scrollIntoView()
ng-click 이벤트 대신 on-tap을 사용해보세요.이런 문제가 있었습니다.검색 양식 레이블 안에 있는 클리어 검색 상자 버튼을 만들어서 해결했고, 클리어 버튼의 ng 클릭을 on-tap으로 대체했습니다.지금은 잘 작동합니다.
언급URL : https://stackoverflow.com/questions/12204571/mobile-safari-javascript-focus-method-on-inputfield-only-works-with-click
'sourcecode' 카테고리의 다른 글
VS 2010에서 C# 앱의 릴리스 빌드를 "디버깅"할 수 있습니까? (0) | 2023.10.01 |
---|---|
ng include를 사용할 경우 추가 DOM 노드 사용을 방지합니다. (0) | 2023.10.01 |
고정된 크기의 배열에 대한 포인터 배열 (0) | 2023.10.01 |
SQLite에서 문자열 연결이 작동하지 않음 (0) | 2023.10.01 |
MySQL 테이블을 UTF-8로 변경하려면 어떻게 해야 합니까? (0) | 2023.10.01 |