2017-12-03 114 views
1

我正在嘗試製作一個即時搜索框。當用戶開始在搜索框中輸入內容時,它會觸發一個javascript事件來隱藏博客文章(#home),而搜索結果將會顯示出來(這部分腳本不包括在下面)。但是,在用戶清除搜索框後,他們只看到空白頁面,因爲#homedisplay仍設置爲none如何在輸入字段被清除時觸發JavaScript事件?

我怎樣才能讓JavaScript的檢測用戶清除提交輸入在#search-input,並#home顯示true一遍嗎?

document.getElementById('search-input').oninput = function() { 
    document.getElementById('home').style.display = 'none'; 
}; 

enter image description here enter image description here enter image description here

回答

2

您可以通過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>

+0

很高興我能幫忙。祝你好運! –

0

感謝卡爾·愛德華茲的幫助!

下面是最終代碼完美的作品:

const searchInput = document.getElementById('search-input'); 
const home = document.getElementById('home'); 
const results = document.getElementById('results'); 

searchInput.addEventListener('input', function() { 
    if (this.value) { 
     home.style.display = 'none'; 
     results.style.display = 'inline'; 
    } else if (!this.value && home.style.display === 'none') { 
     home.style.display = 'block'; 
     results.style.display = 'none'; 
    } 
}); 
相關問題