jroll-fixedinput.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* global define, JRoll */
  2. (function (window, document, JRoll) {
  3. 'use strict'
  4. var utils = JRoll.utils
  5. function _focusin (e) {
  6. var tagName = e.target.tagName
  7. var type = e.target.type
  8. if (e.target === document.activeElement &&
  9. (tagName === 'INPUT' || tagName === 'TEXTAREA') &&
  10. (type === 'text' || type === 'password' || type === 'textarea' || type === 'email' || type === 'number' || type === 'search' || type === 'tel' || type === 'url') &&
  11. window.innerHeight > 460) {
  12. var me = this
  13. var t = utils.computePosition(e.target, document.body).top
  14. var top = utils.computePosition(e.target, me.wrapper).top
  15. // 调整位置
  16. if (t + me.y > window.innerHeight / 2 - 50 && utils.isAndroid) {
  17. me.scrollTo(me.x, -1 * top + window.innerHeight / 2 - me.options.adjustTop, 200, true)
  18. }
  19. }
  20. }
  21. function _focusout () {
  22. var me = this
  23. setTimeout(function () {
  24. if (document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') {
  25. me.scrollTo(me.x, me.y, 200, false, function () {
  26. // 判断绘制的方形顶点是否为正常值,如果不是,表明已被手机自动移动过,需要使用scrollIntoView拉正
  27. if (me.y !== me.scroller.getClientRects()[0].top - utils.computePosition(me.scroller, document.body).top) {
  28. me.scroller.scrollIntoView()
  29. }
  30. })
  31. }
  32. }, 100)
  33. }
  34. JRoll.prototype.fixedinput = function (adjustTop) {
  35. var me = this
  36. // 安卓手机输入表单时自动调整输入框位置
  37. me.options.adjustTop = adjustTop || 100
  38. if (!me.wrapper.jroll_fixedinput) {
  39. me.wrapper.jroll_fixedinput = 1 // 防止多次绑定事件
  40. me.wrapper.addEventListener('click', _focusin.bind(me), false)
  41. me.wrapper.addEventListener('focusout', _focusout.bind(me), false)
  42. }
  43. }
  44. JRoll.prototype.fixedinput.version = '{{version}}'
  45. // CommonJS/AMD/CMD规范导出JRoll
  46. if (typeof module !== 'undefined' && module.exports) {
  47. module.exports = JRoll
  48. }
  49. if (typeof define === 'function') {
  50. define(function () {
  51. return JRoll
  52. })
  53. }
  54. })(window, document, JRoll)