我需要从summernote
中的光标位置获取前一个单词。
我从summernote获得最后一句话。但我需要从光标位置获取前一个单词。
例如 如果编辑器内的文字是" Hello world。你好吗?"和光标是"如何"如果我按空格或输入我需要得到"如何"字。
$(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>
&#13;
答案 0 :(得分:0)
这是一种方法(只是为了注意 - 我并不完全了解你的完整要求。例如,如果退格点击,如果输入第一个单词,打印什么,如果输入单词,点击进入再次输入打字等):
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())
}
}
&#13;
<input id="note-editable" type="text">
&#13;