我发现一段代码的工作方式非常接近我想要的。最终结果是,当您在输入字段中键入内容时,下面会根据文本输入显示相关选项列表。然后,您可以单击这些选项之一,而不必键入完整的字符串。
唯一的问题是,当我尝试将此代码适应我现有的项目时,它会崩溃,因为输入字段被包装在表单中。我将如何修改此代码,使其以完全相同的方式运行,而不必将输入标记包装在表单元素中? IE。只需有一个输入字段。
(
function()
{
var lookFor = [
"Paris",
"Canada",
"England",
"Scotland",
"Brazil",
"Manila",
"Atlanta"
];
var form = document.getElementById("theForm");
var resultsDiv = document.getElementById("results");
var searchInput = form.search;
// first, position the results:
var node = searchInput;
var x = 0;
var y = 0;
while ( node != null )
{
x += node.offsetLeft;
y += node.offsetTop;
node = node.offsetParent;
}
resultsDiv.style.left = x + "px";
resultsDiv.style.top = (y + 20) + "px";
// now, attach the keyup handler to the search field:
searchInput.onkeyup = function()
{
var txt = this.value.toLowerCase();
if ( txt.length == 0 ) return;
var txtRE = new RegExp( "(" + txt + ")", "ig" );
// now...do we have any matches?
var top = 0;
for ( var s = 0; s < lookFor.length; ++s )
{
var srch = lookFor[s];
if ( srch.toLowerCase().indexOf(txt) >= 0 )
{
srch = srch.replace( txtRE, "<span>$1</span>" );
var div = document.createElement("div");
div.innerHTML = srch;
div.onclick = function() {
searchInput.value = this.innerHTML.replace(/\<\/?span\>/ig,"");
resultsDiv.style.display = "none";
};
div.style.top = top + "px";
top += 20;
resultsDiv.appendChild(div);
resultsDiv.style.display = "block";
}
}
}
// and the keydown handler:
searchInput.onkeydown = function()
{
while ( resultsDiv.firstChild != null )
{
resultsDiv.removeChild( resultsDiv.firstChild );
}
resultsDiv.style.display = "none";
}
}
)();
.searchInput {
width: 200px;
}
#results {
display: none;
position: absolute;
width: 200px;
background-color: lightyellow;
z-index: 10;
}
#results div {
position: absolute;
width: 200px;
height: 20px;
background-color: white;
cursor: pointer;
overflow: hidden;
}
#results div:hover {background: lightblue;}
#results div span {
color: red;
font-weight: bold;
}
<form id="theForm">
Search for: <input name="search" class="searchInput"/>
</form>
<div id="results"></div>
最佳答案
因为在这部分代码中它依赖于 form
元素来获取 input
元素:
var form = document.getElementById("theForm");
var resultsDiv = document.getElementById("results");
var searchInput = form.search;
除此之外,不需要表单
。因此,您可以改为:
var resultsDiv = document.getElementById("results");
var searchInput = document.getElementsByClassName("searchInput")[0];
或者将您的 input
元素更改为 id
为 "searchInput"
而不是 class
并且做:
var resultsDiv = document.getElementById("results");
var searchInput = document.getElementById("searchInput");
关于javascript - 删除表单标签但保留输入功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45971760/