我是 JavaScript 的新手,目前我仍在学习它。
我正在尝试创建一个搜索栏,当用户输入元素名称(例如元素 5)时,搜索栏将滚动到基于输入和 Div 标签的元素。我正在处理的网站是一长串元素,客户通常知道他们在寻找什么。
我见过很多关于如何使按钮滚动到 Div 的示例,但关于如何在搜索栏中设置输入以滚动到 Div 的示例并不多。
滚动方式要是流畅就好了。我希望它基于他们输入的数值。因此,如果它是一个字符串,例如“10.01A Paper”,我希望它将它转换为 1001A”,这就是 div 的内容命名。<Div ID=1001A>
这有意义吗?
任何建议都会很棒!
这是一个Demo
<form id="searchbox" action="">
<input id="search" type="text" placeholder="Type here">
<input id="submit" type="submit" value="Search">
第 1 项
第 2 项
第 3 项
第 4 项
.space {
width:100%;
height:500px;
background-color:#FFF;
}
最佳答案
像这样的东西可能有用 jsfiddle :
var searchButton = document.getElementById('submit'),
searchText = document.getElementById('search');
// the text property is what the search input is compared against
// once a match is found, the id property is used to lookup the element
var items = [
{ text: 'Item 1', id: 'item1' },
{ text: 'Item 2', id: 'item2' },
{ text: 'Item 3', id: 'item3' },
{ text: 'Item 4', id: 'item4' }
];
function searchForItem(query) {
for (var i = 0; i < items.length; i++) {
if (items[i].text.indexOf(query) !== -1) {
return document.getElementById(items[i].id);
}
}
}
searchButton.addEventListener('click', function () {
var query = searchText.value,
item = searchForItem(query);
if (typeof item !== 'undefined') {
item.scrollIntoView();
}
});
html:
<input id="search" type="text" placeholder="Type here"/>
<input id="submit" type="button" value="Search" />
<div id="item1" class="space">Item 1</div>
<div id="item2" class="space">Item 2</div>
<div id="item3" class="space">Item 3</div>
<div id="item4" class="space">Item 4</div>
关于滚动到输入 ID 的 JavaScript 搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31392824/