最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Force spell check on a textarea in WebKit - Stack Overflow

programmeradmin4浏览0评论

I'm creating a browser based QC/data entry app that will let people edit OCRed files, which naturally have tons of errors. Chunks of data are put in textareas so they can be checked, but the red underlines only appear when the user manually puts the cursor in a misspelled word.

Is there a way to force WebKit to add the little red spell check underlines to textareas?

I'm creating a browser based QC/data entry app that will let people edit OCRed files, which naturally have tons of errors. Chunks of data are put in textareas so they can be checked, but the red underlines only appear when the user manually puts the cursor in a misspelled word.

Is there a way to force WebKit to add the little red spell check underlines to textareas?

Share Improve this question asked Dec 10, 2009 at 23:24 sakabakosakabako 1,1507 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11 +50

Essentially you need to use the selection api to move the insertion point over each word to get Safari to highlight it. Here's an example to scan over the first thousand words...

textarea = document.getElementById("mytextarea");
textarea.focus();

var selection = window.getSelection();
selection.modify("move", "backward", "line");
for (var i = 0; i < 1000; i++ ) {
    selection.modify("move", "forward", "word");
}

// Remove focus from the element, since the word under
// the cursor won't have a misspelling marker.
textarea.blur();

This code was lifted from the WebKit Layout test suite.

I have no idea if this will actually work or not, but you might want to try playing with the selection stuff. In other words, after you update your textarea (and want to "refresh" it to make the red underline show), you might be able to do something like:

var length = document.getElementById('TEXTAREA#your').value.length;
document.getElementById('TEXTAREA#your').setSelectionRange(0, length);

You can find a bit more on how to use selections here: How do I select arbitrary text on the page using javascript? or via a Google search.

My thinking is that creating a selection (or maybe clearing it after you create it) might trigger a different browser event which causes the spellcheck refresh ... but that's just an idea; it might do the same exact thing as setting textArea.value (ie. nothing).

Great answer from Mark Fowler, here is an improvement on it:

textarea = document.getElementById("mytextarea");
textarea.focus();
var textLength = textarea.value.length;

var selection = window.getSelection();
for (var i = 0; i < textLength; i++ ) {
    selection.modify("move", "backward", "character");
}

// Remove focus from the element, since the word under
// the cursor won't have a misspelling marker.
textarea.blur();

So you can avoid the arbitrary 1000 number and it can handle multiple lines.

发布评论

评论列表(0)

  1. 暂无评论