没有用于访问 Chrome 拼写检查建议的 API,也不会在输入错误的单词时触发任何事件。但是,事件可以实现。
我不知道您使用此功能的用例是什么,但我使用montanaflynn's Spellcheck API on MashApe 进行了演示。该演示会监视一个文本区域,当用户暂停输入时,它会通过 API 发送文本以进行测试。 API 返回的 JSON 包含原始字符串、建议的更正字符串以及包含更正单词及其建议替换的对象。
建议显示在文本区域下方。当建议悬停时,错误输入的单词会突出显示。单击时,错字将替换为建议。
我还添加了一个洗牌功能,它在发送之前对字符串中的单词进行打乱,为 API 的使用增加一层隐私(它也使用 SSL)。 API 和 Chrome 都不使用基于上下文的建议,因此改组不会改变结果。
这里是 CodePen 的链接:http://codepen.io/aecend/pen/rOebQq
这里是代码:
CSS
<style>
* {
font-family: sans-serif;
}
textarea {
margin-bottom: 10px;
width: 500px;
height: 300px;
padding: 10px;
}
.words {
width: 500px;
}
.word {
display: inline-block;
padding: 2px 5px 1px 5px;
border-radius: 2px;
background: #00B1E6;
color: white;
margin: 2px;
cursor: pointer;
}
</style>
HTML
<textarea id="text" placeholder="Type something here..."></textarea>
<div id="words"></div>
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
;(function(){
"use strict";
var words = document.getElementById("words"),
input = document.getElementById("text"),
timeout, xhr;
input.addEventListener("keyup", function(e){
if (timeout) clearTimeout(timeout);
if (!this.value.trim()) words.innerHTML = '';
timeout = setTimeout(function() {
var test_phrase = shuffle_words( input.value );
spell_check(test_phrase);
timeout = null;
}, 500);
});
function shuffle_words(inp) {
inp = inp.replace(/\s+/g, ' ');
var arr = inp.split(" "),
n = arr.length;
while (n > 0) {
var i = Math.floor(Math.random() * n--),
t = arr[n];
arr[n] = arr[i];
arr[i] = t;
}
return arr.join(' ');
}
function spell_check(text){
if (xhr) xhr.abort();
xhr = $.ajax({
url: 'https://montanaflynn-spellcheck.p.mashape.com/check/',
headers: {
'X-Mashape-Key': 'U3ogA8RAAMmshGOJkNxkTBbuYYRTp1gMAuGjsniThZuaoKIyaj',
'Accept': 'application/json'
},
data: {
'text': text
},
cache: false,
success: function(result){
xhr = null;
suggest_words(result);
}
});
}
function suggest_words(obj){
if (!obj.corrections) return;
words.innerHTML = '';
for (var key in obj.corrections) {
if (obj.corrections.hasOwnProperty(key)) {
var div = document.createElement("div");
div.className = "word";
div.innerHTML = obj.corrections[key][0];
div.orig = key;
div.onmouseover = function() {
var start = input.value.indexOf(this.orig);
input.selectionStart = start;
input.selectionEnd = start + this.orig.length;
};
div.onmouseout = function() {
var len = input.value.length;
input.selectionStart = len;
input.selectionEnd = len;
}
div.onclick = function() {
input.value = input.value.replace(this.orig, this.innerHTML);
this.parentNode.removeChild(this);
}
words.appendChild(div);
}
}
}
})();
</script>
我只使用 jQuery 来简化此演示的 AJAX 请求。这可以在 vanilla JS 中轻松完成。