html拖拽没有文字不能拖拽,优雅的防止页面文字选中拖拽问题?

有时页面上的文本被鼠标框选、键盘全选等操作,导致触发鼠标的拖拽机制,这对web体验很差,如图

ee3065d0e5a6858f459add8f5747c71f.png图中的文本和图片等很容易被鼠标所框选或手贱全选操作,接着鼠标再一拖,那场面就很尴尬了。

如何优雅地解决这样的麻烦?

试过监听页面body的选中和拖拽事件,效果非常明显,直接阻止了除输入/文本框以外的所有的选中和拖拽,代码如下。但是有个缺陷,部分dom(非文本/输入框)上的文本希望保留被框选的功能,这效果明显过头了,不太适合。document.body.onselectstart = document.body.ondrag = ()=>{ return false }

试着通过CSS来阻止,代码如下。效果和上面的方案一样,缺陷也一致body{  -webkit-touch-callout: none;

-webkit-user-select: none;

-khtml-user-select: none;

-moz-user-select: none;

-ms-user-select: none;

user-select: none;

}

接着缩小范围,但是发现只要有文本能选中,鼠标就能触发拖拽机制,通过单独禁止body的拖拽也无效

document.body.ondrag = ()=>{ return false }

如何才能做到只能选,不能拖

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过重载 QPlainTextEdit 的 mousePressEvent、mouseMoveEvent、mouseReleaseEvent 三个事件来实现自定义框选文字然后拖拽的功能。 具体实现步骤如下: 1. 在 mousePressEvent 中记录下起始位置,清空选中的文本。 2. 在 mouseMoveEvent 中计算出当前鼠标所在位置,然后设置选中的文本。 3. 在 mouseReleaseEvent 中根据选中的文本来确定是否要进行拖拽操作。 下面是一个简单的示例代码,演示了如何自定义框选文字并进行拖拽: ```python from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit from PyQt5.QtCore import Qt, QPoint class MyTextEdit(QPlainTextEdit): def __init__(self, parent=None): super(MyTextEdit, self).__init__(parent) self._is_dragging = False self._start_pos = QPoint(0, 0) self._end_pos = QPoint(0, 0) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self._start_pos = event.pos() self._end_pos = event.pos() self.setTextCursor(self.cursorForPosition(event.pos())) self.setTextCursor(self.textCursor()) self.setTextCursor(Qt.IBeamCursor) self.clearFocus() def mouseMoveEvent(self, event): if event.buttons() == Qt.LeftButton: self._end_pos = event.pos() start = self.cursorForPosition(self._start_pos) end = self.cursorForPosition(self._end_pos) cursor = self.textCursor() cursor.setPosition(start.position(), QTextCursor.MoveAnchor) cursor.setPosition(end.position(), QTextCursor.KeepAnchor) self.setTextCursor(cursor) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: if self._is_dragging: self._is_dragging = False self.setCursor(Qt.IBeamCursor) else: self._is_dragging = True def mouseDoubleClickEvent(self, event): if event.button() == Qt.LeftButton: self.clearFocus() if __name__ == '__main__': app = QApplication([]) window = QMainWindow() text_edit = MyTextEdit() window.setCentralWidget(text_edit) window.show() app.exec_() ``` 在这个示例中,我们重载了 QPlainTextEdit 的 mousePressEvent、mouseMoveEvent、mouseReleaseEvent 和 mouseDoubleClickEvent 四个事件。其中,mousePressEvent 记录下了起始位置,并清空了选中的文本;mouseMoveEvent 计算出当前鼠标所在位置,并设置选中的文本;mouseReleaseEvent 根据选中的文本来确定是否要进行拖拽操作;mouseDoubleClickEvent 清除了焦点。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值