[英]How to I use the detect key function to go to the next section in Javascript?
So I'm playing with detecting keystrokes in JavaScript and I thought it would be cool to add a function to my site that would go to the next section when the down arrow is pressed and go to the previous section when the up arrow is pressed, I'm not sure how I should go about this, the source code is a bit too long to put here so my site is just https://www.hukari.tech/ , if any of you have ideas, please let me know.所以我正在玩检测 JavaScript 中的击键,我认为向我的网站添加一个函数会很酷,当按下向下箭头时会转到下一部分,当按下向上箭头时会转到上一部分,我不知道我应该怎么做,源代码有点长,不能放在这里,所以我的网站只是https://www.hukari.tech/ ,如果你们有任何想法,请告诉我. Thanks so much :)
非常感谢 :)
This is a good start, but depending on how you have your site structured you will have to handle navigation differently.这是一个好的开始,但根据您的网站结构,您将不得不以不同的方式处理导航。 You can use cookies or local storage to track which page was last visited to send the client to the previous page.
您可以使用 cookie 或本地存储来跟踪上次访问的页面,以将客户端发送到上一个页面。 You can use
window.history.back()
to simulate the back button being pressed.您可以使用
window.history.back()
来模拟被按下的后退按钮。 If it is a single page site, you can scroll to different tags on the page, keeping track of where the client is with a global variable the keydown function checks.如果它是单页站点,您可以滚动到页面上的不同标签,使用 keydown 函数检查的全局变量跟踪客户端的位置。
const body = document.querySelector("body"); const loadNextPage = () => body.innerText = "Next"; const loadPreviousPage = () => body.innerText = "Previous"; window.addEventListener("keydown", e => { if(e.key == "ArrowUp") { e.preventDefault(); //to prevent it from doing native scroll loadPreviousPage(); } if(e.key == "ArrowDown") { e.preventDefault(); //to prevent it from doing native scroll loadNextPage(); } });
* { background: lightgray; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.