700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > H5监听键盘弹起收回 用法超简单!兼容Android iOS。

H5监听键盘弹起收回 用法超简单!兼容Android iOS。

时间:2020-08-30 07:24:02

相关推荐

H5监听键盘弹起收回 用法超简单!兼容Android iOS。

引入以下代码,仅需2行代码即可监听!

/*** 兼容Android、iOS各浏览器* H5键盘监控弹出(KeyboardUp)、收起(KeyboardDown)事件定义* auth: huaicheng151201@* time: .11.20* 用法:* 与click事件的绑定用法无异,如:window.addEventListener("KeyboardUp",function() {//键盘弹起来了},false);window.addEventListener("KeyboardDown",function() {//键盘收起来了},false);**/;(function(window){if(!window || !navigator) return;var u = navigator.userAgent;var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);var KeyboardUpEvent = document.createEvent("KeyboardEvent");KeyboardUpEvent.initEvent("KeyboardUp",true,true);var KeyboardDownEvent = document.createEvent("KeyboardEvent");KeyboardDownEvent.initEvent("KeyboardDown",true,true);if(isAndroid) {var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;window.onresize = function () {var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;if (resizeHeight - 0 < originalHeight - 0) {document.dispatchEvent(KeyboardUpEvent);} else {document.dispatchEvent(KeyboardDownEvent);}}} else if(isiOS){document.body.addEventListener('focusin', () => {document.dispatchEvent(KeyboardUpEvent);})document.body.addEventListener('focusout', () => {document.dispatchEvent(KeyboardDownEvent);})} else {throw "无法识别浏览器机型,请检查navigator.userAgent是否被重新定义过."}})(window);

然后,需要在监听的地方:

window.addEventListener("KeyboardUp",function() {//"键盘弹起来了";},false);window.addEventListener("KeyboardDown",function() {//"哎呀,键盘收起来了";},false);

开心的玩耍去吧!!!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。