我创建了一个搜索框,当用户对其进行搜索时,将重点放在用户搜索上。如果我搜索关于的,它将集中在标题“About”上,然后我滚动到底部或向上,再次搜索有关--它没有关注任何东西。
function Focus() {
var search = document.getElementById("search-box").value;
if (search.toLowerCase() == "about") {
window.location.hash = '#about';
document.getElementById("search-box").value = "";
console.log("about")
} else if (search.toLowerCase() == "skills") {
window.location.hash = '#skill';
document.getElementById("search-box").value = "";
console.log("skills")
} else if (search == "") {
alert("Search Field is empty. Type anything");
} else {
alert("Not Found");
document.getElementById("search-box").value = "";
}
}
<input type="search" id="search-box" placeholder="Search">
<button type="submit" id="searchbar" onclick="Focus()">Search</button>
<h1 id="about">About</h1>
<h1 id="skill">Skills</h1>
<!-- There are so many things under this titles. -->
发布于 2021-09-14 09:49:22
正如@Balaji Sivasakthi已经回答的那样,我想指出,您重复了很多代码。
如果要清除搜索框,则不需要在每个if语句中都写入
getElementById
.search
,也可以将该变量作为变量使用(下面的element
),您可以检查它是否为message
变量,并在if语句之外放置警告。如果消息有除"“以外的任何值,则触发警报.
function Focus() {
var searchBox = document.getElementById("search-box")
var search = searchBox.value.toLowerCase(); // 2
var element = document.getElementById(search); // 2 & 3
var message = ""; // 4
window.location.hash = '#';
if (element) { // 3 -- checks if you found any elements with id #{search}
window.location.hash += search; // adds element id to hash
console.log({search});
} else if (search) { // 2 & 4 -- anything else than "" is true
message = "Not Found";
} else {
message = "Search Field is empty. Type anything"
}
searchBox.value = ""; // 1
if (message) { alert(message) } // 4 -- anything else than "" is true
}
<input type="search" id="search-box" placeholder="Search">
<button type="submit" id="searchbar" onclick="Focus()">Search</button>
<h1 id="about">About</h1>
<h1 id="skills">Skills</h1>
<!-- There are so many things under this titles. -->
发布于 2021-09-14 09:23:46
在分配新哈希之前清除哈希。window.location.hash = '';
if (search.toLowerCase() == "about") {
window.location.hash = '';
window.location.hash = '#about';
document.getElementById("search-box").value = "";
}
else if(search.toLowerCase() == "skills") {
window.location.hash = '';
window.location.hash = '#skill';
document.getElementById("search-box").value = "";
}
else if(search==""){
alert("Search Field is empty. Type anything");
}
else{
alert("Not Found");
document.getElementById("search-box").value = "";
}
发布于 2021-09-14 09:30:34
问题是,当您搜索相同的散列两次时,散列(#约)不会改变。只有当散列发生变化时,浏览器才会滚动。
我认为最好的方法是在搜索按钮上搜索元素,得到元素的偏移量,然后滚动到该位置:
获取元素的偏移量:
element.getBoundingClientRect().top + document.documentElement.scrollTop
滚动到位置
window.scroll(x, y)
https://stackoverflow.com/questions/69175033
复制相似问题