移动端长按文字会出现 “复制 全选”的默认弹框(这里拿安卓举例)
但是有的时候需要在长按的时候增加别的功能 这时候就需要禁用原生的弹框然后重写自己的功能
第一步:禁用掉原生弹窗 但是支持划选文字
重要css属性:
-webkit-touch-callout: none;
ps:-webkit-touch-callout: none;
是 CSS 样式属性,通常用于在WebKit内核的浏览器(如Chrome和Safari)中禁止长按链接或图片时默认的弹出菜单。这个属性可以帮助开发者在移动端网页开发中控制长按元素时的行为。
当你在某个元素上应用 -webkit-touch-callout: none;
样式时,长按该元素不会触发默认的弹出菜单,比如在图片上长按不会出现保存图片的选项,或者在链接上长按不会出现打开链接或复制链接的选项。
例如,可以将这个样式应用于图片元素来禁用默认的弹出菜单:
img {-webkit-touch-callout: none;
}
需要注意的是,这个样式属性仅在WebKit内核的浏览器中生效,其他浏览器可能需要使用不同的样式属性来实现类似的效果
现在就可以看到 文字长按有选中的区域 但是不会再弹出原生的复制全选了。
下一步需要实现长按弹出自己封装的弹框
第二步:长按触发事件:
<template><div @touchmove="onTouchMove($event)"@touchstart="touchstart($event, msgObject)"@touchend="emptyTime()">{{'内容'}}<div>
</template><script>methods: {touchstart(e,val){// returnconsole.log(e,val)console.log('touchstart val====', val);// if (this.msgObject.msgFrom == '3' && this.msgObject.refSessionId)this.toucheX = e.targetTouches[0].screenXthis.toucheY = e.targetTouches[0].screenYclearTimeout(this.Loop); //再次清空定时器,防止重复注册定时器this.Loop = setTimeout(function() {e.preventDefault()let nodeArr = document.getElementsByClassName("dropdown-content")if(Array.from(nodeArr).length>0){Array.from(nodeArr).forEach(item => {item.style.display = 'none'})}let nodeArrs = document.getElementsByClassName("dropdown-content-user")if(Array.from(nodeArrs).length>0){Array.from(nodeArrs).forEach(item => {item.style.display = 'none'})}}.bind(this), 800);console.log('touchstart事件触发了222')// 清除全局下的回复弹框this.removeReference()// this.$emit('on-touchstart',e)}, // 长按结束清空定时器emptyTime:function (e) {clearTimeout(this.Loop); //清空定时器,防止重复注册定时器},// 滑动的话取消长按监听onTouchMove (e) {const moveX = e.targetTouches[0].screenXconst moveY = e.targetTouches[0].screenY// 解决vivo机型,手指没有move,touchmove事件仍然会调用而导致setTimeout被clearif (this.toucheX !== moveX || this.toucheY !== moveY) {// 手指滑动,清除定时器,中断长按逻辑this.Loop && clearTimeout(this.Loop)}},
}
</script>
tourchStart里面放置长按要触发的事件 可以是展示自己重写的弹框显示事件
第三步: 实现复制功能:
使用的是vue-clipboard2": "^0.3.3"插件
弹框里面的复制按钮的代码:
<div@touchstart.stop@click.stop="copyMsgContent"v-clipboard:copy="copyContent"v-clipboard:success="onCopy"v-clipboard:error="onError"v-if="msgObject.msgType == '1'"class="app-tools-content"><img src="../../assets/imgs/app_tools_copy.svg" /><p>复制</p></div>
copyMsgContent方法:
copyMsgContent () {
const selectText = window.getSelection().toString()? window.getSelection().toString(): this.mobileSelectContent? this.mobileSelectContent: ""; // 获取当前window滑选的文字
this.copyContent = str; // 给绑定的copyContent赋值
}
这样就实现了重写复制的功能~