我正在尝试制作一个即时搜索框。当用户开始在搜索框中输入内容时,它会触发一个 javascript 事件来隐藏博客文章 (#home
) 并显示搜索结果(下面不包含这部分脚本)。然而,在用户清除搜索框后,他们看到的只是一个空白页面,因为 #home
的 display
仍设置为 无
。
我如何让 JavaScript 检测到用户在 #search-input
处清除了输入字段 并使 #home
显示 true
又是?
document.getElementById('search-input').oninput = function() {
document.getElementById('home').style.display = 'none';
};
最佳答案
您可以通过 input
事件监听器执行此操作。要隐藏 #home
元素,请添加一个条件来检查输入是否有值。如果没有,则将其隐藏。要将其取回,您可以执行相反的操作,但仅如果#home
被隐藏:
const searchInput = document.getElementById('search-input');
const home = document.getElementById('home');
searchInput.addEventListener('input', function() {
if (!this.value) {
home.style.display = 'none';
} else if (this.value && home.style.display === 'none') {
home.style.display = 'block';
}
});
<input id="search-input" type="text"/>
<div id="home">
Sample Content
</div>
关于javascript - 如何在清除输入字段时触发 JavaScript 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614523/