我需要从 summernote
中的光标位置获取上一个单词。
我收到了 Summernote 的最后一句话。但我需要从光标位置获取前一个单词。
例如 如果编辑器内的文本是“Hello world. How are you?”光标位于“如何”之后,如果我按空格或输入,我需要获取“如何”一词。
$(document).ready(function(){
$('.description').summernote({
height: 300,
callbacks: {
onKeyup: function(e){
//32 => space
//13 => enter
if(e.which == 32 || e.keyCode == 13){
var lastword = $('.note-editable').text().replace(/\s+$/, '').split(/(\s| )/).pop();
console.log(lastword);
}
}
}
});
});
.content{
width: 800px;
margin: 0 auto;
margin-top: 50px;
}
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote-bs4.css" />
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote-bs4.js"></script>
</head>
<body>
<div class="content">
<textarea class="description"></textarea>
</div>
</body>
</html>
最佳答案
这是一种方法(只是要注意 - 我不完全了解您的完整要求。例如 - 如果单击退格键怎么办,如果输入第一个单词要打印什么,如果输入单词,然后再次单击 Enter 会怎样打字等):
var inp = document.getElementById('note-editable');
// creating a Set so if space or enter clicked twice, its index wouldn't be captured twice
// could be done without this, but might help the future if need to select different words
var spaces = new Set([0]);
inp.addEventListener("keyup", getWord);
function getWord(e) {
if(e.which == 32 || e.keyCode == 13){
// selectionEnd property prints the position of input charecter
let spacePos = e.srcElement.selectionEnd;
spaces.add(spacePos);
let arr = Array.from(spaces);
let curSpacePos = arr.indexOf(spacePos);
let prevSpacePos = arr.indexOf(spacePos) - 1;
var res = Array.from(inp.value);
console.log(res.slice(arr[prevSpacePos -1], arr[curSpacePos - 1]).join('').trim())
}
}
<input id="note-editable" type="text">
关于javascript - 从 Summernote 中的光标位置获取上一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47950318/