滚动到输入 ID 的 JavaScript 搜索栏

标签 javascript html css

我是 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/

相关文章:

html - HTML/CSS 中的像素与点

html - 无法让文本环绕 WordPress 主题中的侧边栏容器

javascript - 如何在另一个函数中调用一个jquery函数

javascript - RxJS 5, Angular : How to do a request every x seconds UNTIL a message matches a certain string?

java - 使用 bufferedimage java 设置图像 src

javascript - 通过JQuery改变背景图片

javascript - TypeScript:数组属性在填充时导致此错误: "TypeError: Cannot set property ' 0' of undefined"

javascript - Web Audio API Recording 适用于 Firefox 但不适用于 Chrome

html - 防止 CSS 网格中的双边框

javascript - 同位素元素的定位