IOS由于Fastclick导致contentEditable无法聚焦

1. 问题描述

在IOS浏览器,用div模拟textarea实现可换行的编辑输入文本,在Vue条件下加入了fastclick防重点击,fastclick判断ontouchstart条件看是否是移动端,若是移动端则进行相应的事件绑定,移动端点击触发的顺序ontouchstart => ontouchend => click,由于在ios条件下ontouchend方法若needsClick(button、select、textarea、input、label、iframe、video or className contains 'needsclick')为不可点击时防止了事件冒泡(preventDefault),所以出现无法点击情况。

2. 解决问题方

添加可编辑类needsclick,使div可编辑状态,去掉fastclick防止冒泡,如下

<style>

.needsclick{content: attr(placeholder);color: #B8B8B8;}

</style>

<div contentEditable="true" class="needsclick" placeholder="请输入详细地址"></div>

3. fastclick部分源码分析具体不能编辑原因

首先,我们要了解事件的分发过程,ontouchstart => ontouchend => click,针对于这点,我们可知道要是ontouchend阻塞了,会导致无法聚焦,最终div无法编译,下面是fastclick的可编辑的部分判断源码:

FastClick.prototype.needsClick = function(target) {

switch (target.nodeName.toLowerCase()) {
        // Don't send a synthetic click to disabled inputs (issue #62)
        case 'button':
        case 'select':
        case 'textarea':
            if (target.disabled) {
                return true;
            }
            break;
        case 'input':
            // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
            if ((deviceIsIOS && target.type === 'file') || target.disabled) {
                return true;
            }
            break;
        case 'label':
        case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
        case 'video':
            return true;
        return (/\bneedsclick\b/).test(target.className); // 正则表达,className具有needsclick即可编辑
    };

再者看ontouchend方法

 if (!this.needsClick(targetElement)) {

      event.preventDefault();

      this.sendClick(targetElement, event);

  }

即若不添加needsclick则会执行preventDefault防止向上冒泡

对于android为什么就不会出现无法输入的情况呢?由于android手机webview没有触发ontouchend事件

若有错误,或更多问题,请多多指教,谢谢

猜你喜欢

转载自blog.csdn.net/soft_z1302/article/details/83104461