我正在尝试创建一个功能强大的搜索框,以突出显示文本中的单词。但是,我无法通过按 Enter 进行搜索。您有什么建议吗?代码中的缺陷在哪里?谢谢!
HTML:
<form>
<input type="text" id="search" onkeypress="if (e.keycode==13) doSearch(document.getElementById('search').value)" placeholder="What are you looking for?">
</form>
JavaScript:
function doSearch(text)
{
if (window.find && window.getSelection)
{
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text))
{
document.getElementById("search").blur();
document.execCommand("HiliteColor", false, "green");
sel.collapseToEnd();
}
document.designMode = "off";
}
else if (document.body.createTextRange)
{
var textRange = document.body.createTextRange();
while (textRange.findText(text))
{
textRange.execCommand("BackColor", false, "green");
textRange.collapse(false);
}
}
}