有没有一种方法可以检测文本选择时的鼠标单击或鼠标向上事件,但在选择文本时实际上会跳过?
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'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>
Run Code Online (Sandbox Code Playgroud)
这是我的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');
}
});
})
Run Code Online (Sandbox Code Playgroud)
所需的解决方案是仅当我单击所选文本时状态文本才为真,但在我选择时则不然。
您可以添加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');
}
});
});Run Code Online (Sandbox Code Playgroud)
#status {
font-weight: bolder;
color: red;
}Run Code Online (Sandbox Code Playgroud)
<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'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>Run Code Online (Sandbox Code Playgroud)
我已经更改e.target.contains(window.getSelection().baseNode);为,window.getSelection().containsNode(e.target, true);因为e.target.contains(window.getSelection().baseNode);似乎总是false在 FireFox 中。
| 归档时间: |
|
| 查看次数: |
1923 次 |
| 最近记录: |