h5 嵌入原生 App 项目中遇到的需求。第一次做,记录一下。react+hooks
1 2 3 4 5 6
| let myInput = document.createElement('input'); myInput.value = document.getElementById(doomId).innerHTML; document.body.appendChild(myInput); myInput.select(); // 选择以哪个DOM对象作为模板 document.execCommand('copy'); myInput.parentNode.removeChild(myInput);
|
长按事件 触发弹框提示(复制按钮。举报按钮)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const contentTouchStart = (e, obj, type) => { // e.stopPropagation(); //这两行是为了阻止出现浏览器菜单 // e.preventDefault();
obj.type = type; setTimer( setTimeout(() => { console.log('开始长按 :>> '); setCurrentLongPress(obj); }, '500') ); }; const contentTouchEnd = () => { console.log('结束长按 :>> '); clearTimeout(timer); setTimer(null); };
|
难点:长按什么位置就在什么位置弹出提示框,点击空白处进行弹框的隐藏。
1.dom 元素绑定 id 值,id 值为列表数据的 id,确保唯一。 2.长按事件触发后,记录所触发事件的列表数据 id 值。(current.id) 3.通过 item.id === current.id (伪代码)来控制提示框的显示与隐藏。 4.添加全局监听事件,并屏蔽所有点击事件的冒泡,只触发自己的时间。不触发 document 的监听。 5.当点击空白区域时触发 document 的监听,清除长按事件记录的 id 值,即可实现隐藏弹出框。
stopImmediatePropagation 防止对事件流中当前节点中和所有后续节点中的事件侦听器进行处理。此方法会立即生效,并且会影响当前节点中的事件侦听器。
stopPropagation 防止对事件流中当前节点的后续节点中的所有事件侦听器进行处理。此方法不会影响当前节点 (currentTarget) 中的任何事件侦听器。
记得要在 useEffect 的第二个 return 参数中 清除定时器,清除监听的绑定事件
1 2 3 4 5 6 7 8 9 10 11
| useEffect(() => { document.addEventListener('click', hideInform); return componentWillUnMount; }, []); function componentWillUnMount() { document.removeEventListener('click', hideInform); } const hideInform = () => { console.log('隐藏 :>> '); setCurrentLongPress(null); };
|