Last active
October 21, 2019 04:34
-
-
Save incleaf/5aa05c4b18c70d876488d3e0e921819d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !('MSStream' in window); | |
var isAndroid = /android/i.test(navigator.userAgent) && !isTrident; | |
var isOtherFocusing = false; | |
/** | |
* @param {number} offsetY | |
*/ | |
function scrollTo(offsetY) { | |
Promise.resolve(null).then(function () { | |
window.scrollTo(0, offsetY); | |
}); | |
} | |
/** | |
* @param {HTMLElement} $elem | |
*/ | |
function tweakWebviewTextField($elem) { | |
/** | |
* 안드로이드에서 키보드가 열리면 input이 키보드에 가려질 수 있다. | |
* 포커스 후 인풋이 화면에 정상적으로 보이도록 스크롤을 조정한다. | |
*/ | |
if (isAndroid) { | |
setTimeout(function () { | |
if (!($elem && typeof $elem.getBoundingClientRect === 'function')) { | |
return; | |
} | |
var scrollYOffset = getScrollYOffset(); | |
var rect = $elem.getBoundingClientRect(); | |
var top = rect.top; | |
var height = rect.height; | |
scrollTo(scrollYOffset + top - height); | |
}, 300); | |
} else if (isIOS) { | |
/** | |
* iOS에서 키보드가 열리면 화면 하단에 키보드를 위한 높이가 추가되는데, | |
* 키보드가 닫히더라도 스크롤하기 전까진 해당 영역이 남아있다. 이를 강제로 스크롤해서 영역을 없앤다. | |
*/ | |
window.requestAnimationFrame(function () { | |
setTimeout(function () { | |
if (!($elem && typeof $elem.getBoundingClientRect === 'function')) { | |
return; | |
} | |
/** | |
* input에 포커싱 된 상태에서 바로 다른 input으로 포커스를 이동할 때에는 트윅을 적용하지 않는다. | |
*/ | |
if (!isOtherFocusing) { | |
scrollTo($elem.getBoundingClientRect().top); | |
} | |
}, 0); | |
}); | |
} | |
} | |
function patchWebviewTextFields() { | |
['input', 'select'].forEach(function (selector) { | |
document.querySelectorAll(selector).forEach(function ($element) { | |
$element.addEventListener('focus', function () { | |
isOtherFocusing = true; | |
if ($element.hasAttribute('data-android-scrollOnFocus') && isAndroid) { | |
tweakWebviewTextField($element); | |
} | |
}); | |
$element.addEventListener('blur', function () { | |
isOtherFocusing = false; | |
if ($element.hasAttribute('data-ios-scrollOnBlur') && isIOS) { | |
tweakWebviewTextField($element); | |
} | |
}); | |
}); | |
}); | |
} | |
patchWebviewTextFields(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment