移动端tap事件无视disabled属性

移动端项目中获取手机验证码的操作,其中引用到jquery-2.2.4.min.js和jquery.mobile.custom.min.js,先上代码:

<input class="code_btn" type="button" value="获取验证码" />

js(问题代码):

    /* 点击获取验证码 */
    $(document).on('tap', '.code_btn', function () {
      if (!/^[1]([3-9])[0-9]{9}$/.test($('.mobile_input').val())) {
        toast.show('手机号码格式不正确');
      } else {
        countDown();   //倒计时函数
        getMobileCode($('.mobile_input').val());
      }
    });

问题:

点击获取验证码按钮后,开始倒计时,F12查看如图所示,input标签已经有了disabled属性。
理想状态是:此时该按钮是禁用状态,并不可点击。
但现实是:依然可以点击并触发tap事件。
后来将tap改为click事件后,就一切正常(按钮禁用,不会触发点击事件)。

解决:

根据 jQuery Mobile API 文档的描述,tap 事件背后是 vclick 事件:

Warning: Use tap with caution
Tap makes use of vclick and therefore should be used with caution on touch devices. See the vclick API documentation for more details.

vclick 文档似乎没有写明实现方式。找源码粗略地看了一下,在移动端应该是使用的 touchend 事件。

而在 HTML 5.x 标准里,input 元素的 disabled 属性的值被进一步表述为 form control 的状态,可以参阅 The input element - HTML 5.1 2nd Edition: 4.10. Forms | w3.org。同时,一个 disabled 了的 form control 被设定为不接收任何用户指定的 click 事件:

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

MDN 对 input 元素 disabled 属性的描述中也可以找到相关说明:

Specifically, disabled inputs do not receive the click event, and disabled inputs are not submitted with the form.

所以 touchend 事件不会被屏蔽,tap 事件自然也会正常触发,click 事件则被阻止。

附:
jquery中改变input的disabled状态:

$('.code_btn').attr('disabled','disabled');
$('.code_btn').removeAttr('disabled');
posted @ 2020-08-14 10:32  ZerlinM  阅读(282)  评论(0编辑  收藏  举报