gpt4 book ai didi

javascript - 检测鼠标点击文本选择但在选择文本时忽略?

转载 作者:行者123 更新时间:2023-12-04 13:12:20 25 4
gpt4 key购买 nike

有没有办法检测文本选择时的鼠标单击或鼠标向上事件,但在选择文本时实际上会跳过?
https://jsfiddle.net/chille1987/ctm4rd7n/

<div id="editor">
<p>What is Lorem Ipsum?</p>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>

</div>

<div id="status"></div>
这是我的js代码
$(function() {
$('#editor').on('mouseup', function(e) {
let selection = window.getSelection().toString().length;
let targetContainsSelection = e.target.contains(window.getSelection().baseNode);

if(selection > 0 && targetContainsSelection) {
$('#status').text('true');
} else {
$('#status').text('false');
}
});
})
不理想的解决方案是仅当我单击选定的文本而不是当我选择时才使状态文本为真。

最佳答案

您可以添加 mousedown监听器并跟踪操作开始时(单击或选择)是否有选择。这是一个例子:

$(function() {
let hasSelection = false;
$('#editor').on('mousedown', function() {
hasSelection = document.getSelection().toString().length;
}).on('mouseup', function(e) {
if (hasSelection) {
let selection = window.getSelection().toString().length;
let targetContainsSelection = window.getSelection().containsNode(e.target, true);

if (selection > 0 && targetContainsSelection) {
$('#status').text('TRUE').css('color', 'green');
}
} else {
$('#status').text('FALSE').css('color', 'red');
}
});
});
#status {
font-weight: bolder;
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="status">FALSE</div>
<div id="editor">
<p>What is Lorem Ipsum?</p>

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>

</div>

我已更改 e.target.contains(window.getSelection().baseNode);window.getSelection().containsNode(e.target, true);因为 e.target.contains(window.getSelection().baseNode);似乎总是 false在火狐中。

关于javascript - 检测鼠标点击文本选择但在选择文本时忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63851107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com