【问题标题】:onkeydown navigate forward and backward with arrows keyonkeydown 使用箭头键向前和向后导航
【发布时间】:2021-11-07 05:43:57
【问题描述】:

我尝试使用向左和向右箭头键导航 onkeydown 抛出我的网站。 使用我的字体很棒的链接它可以工作,但我希望它也可以使用我键盘上的箭头键在 onkeydown 上工作。

一个问题是,我的网站使用德语和英语的本地化。这就是为什么我的网址看起来像这样:

https://www.example.com/de https://www.example.com/en

https://www.example.com/de/Arbeiten https://www.example.com/en/Projects

这是我的 HTML:

<div>
    <a href="{{ route('contact') }}" onkeydown="if(e.keyCode == 37) ? window.location.href={{ route('contact')  }} : " class="left-arrow arrow-home-left">
        <i class="fas fa-angle-left fa-5x"></i>
    </a>
</div>


<div>
    <a href="{{ route('projects') }}" onkeydown="if(e.keyCode == 39) ? window.location.href={{ route('projects') }} : " class="right-arrow arrow-home-right">
        <i class="fas fa-angle-right fa-5x"></i>
    </a>
</div>

还有我的 CSS:

body {
  background-color: green;
}

.arrow-home-right {
    display: inline;
    top: 50%;
    right: 0;
    color: white;
    background-color:red;
    position: fixed;
}

.arrow-home-left {
    display: inline;
    top: 50%;
    left: 0;
    color: white;
    background-color:red;
    position: fixed;
}

.arrow-home-right:hover, .arrow-home-left:hover {
    display: inline;
    color: black;
}

这是我的 JSFiddle: https://jsfiddle.net/djosxy7z/15/

我想用 onkeydown 方向键跳转到下一个站点/页面。使用字体很棒的链接它可以工作,但不能使用键盘。

希望有人能给我一个提示。 :)

e:必须要在body上调用onkeydown函数吗?

【问题讨论】:

  • 是的,你必须使用body标签,如下所示。

标签: javascript html jquery onkeydown


【解决方案1】:

您可以使用 body 标签捕获 keydown 事件。这是一个例子:

<body onload="onload_handler()">
    <div>
        <a  href="{{ route('contact')}}" class="left-arrow arrow-home-left">
            <i class="fas fa-angle-left fa-5x"></i>
        </a>
    </div>
    <p></p>
    <div>
        <a  href="{{ route('projects')}}"  class="right-arrow arrow-home-right">
            <i class="fas fa-angle-right fa-5x"></i>
        </a>
    </div>
    <script>
    function onload_handler() {
        document.body.addEventListener("keydown", keydown_handler);
    }
    function keydown_handler(e) {
        let txt = "keydown_handler: keycode = " + e.keyCode;
        let anchor = 0;
        if(e.keyCode == 37) {
            anchor = document.body.querySelector(".left-arrow")
            txt = txt + ": left arrow";
        } else if(e.keyCode == 39) {
            anchor = document.body.querySelector(".right-arrow")
            txt = txt + ": right arrow";
        }
        if(anchor)
            txt = txt + ": " + anchor.href;
        console.log(txt);
        if(anchor)
            anchor.click();
    }
    </script>
</body>

Here is a link to the same site,您使用上面的示例发布了您的小提琴。该示例显示了您在控制台中按了哪些键。

【讨论】:

  • 哇..谢谢!!这正是我想要的:D
猜你喜欢
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
  • 2012-01-27
相关资源
最近更新 更多