如何在 keydown 上使用 Javascript 模拟悬停? [英] How do I simulate hover with Javascript on keydown?

查看:8
本文介绍了如何在 keydown 上使用 Javascript 模拟悬停?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想只使用原生 JavaScript 来完成这项任务.

First of, I'd like to use only native JavaScript to complete this task.

假设我要制作一个自定义下拉菜单,HTML 代码看起来像这样.

Let's say I am to make a custom dropdown, and the HTML code looks kind of like this.

<div class="dropdown">
  <span class="dropdown-label" style="display:block">Select a thing</span>
  <ul class="dropdownItemContainer">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
  </ul>
</div>

在 CSS 文件中,我有类似的东西:

In the CSS file I have something close to this:

ul.dropdownItemContainer li:hover {
  background-color: #FF0000;
}

是的,确实没有下拉行为,但实际上这不是讨论的重点.问题是我想不出一种体面的方法来为此下拉菜单启用键盘控制.期望的结果如下:我按下向下键,第一个选项被突出显示;我再次按下它,第二个选项被突出显示,依此类推.

Yeah, there's really no dropdownish behavior, but it's not the point of discussion actually. The problem is that I couldn't think of a decent way to enable keyboard control for this dropdown. The desired outcome is the following: I press the down key, and the first option is highlighted; I press it again, and the second option is highlighted and so on.

此时我看到的唯一选择(刚开始学习 JS)是获取 ul 的所有子项,将它们粘贴到一个数组中,并通过每当按下向下键时,JS 都会以正确的方式调用.

The only option that I see at this point (just started studying JS) is to fetch all of the ul's children, stick'em into an array and assign the tags a background color through JS methods in a proper way whenever the down key is pressed.

另一方面,我仍然有鼠标控制的 CSS 中描述的 :hover 行为.有模拟悬停的聪明方法吗?

On the other hand, I still have the :hover behavior described in the CSS for mouse countrol. Is there a smart way of simulating hovers?

推荐答案

我会在你的 li 元素上简单地分配一个类,并使用 keydown 处理程序来引导它.以下代码并不完整,而是为您提供一些可以使用的东西.

I would go with a simple assignment of a class on your li-elements and steer it with a keydown handler. The following code is not meant to be complete but give you something you can work with.

var active = document.querySelector(".hover") || document.querySelector(".dropdownItemContainer li");

document.addEventListener("keydown",handler);
document.addEventListener("mouseover",handler);

function handler(e){
    console.log(e.which);
        active.classList.remove("hover");
    if (e.which == 40){
        active = active.nextElementSibling || active;
    }else if (e.which == 38){      
        active = active.previousElementSibling || active;
    }else{
        active = e.target;
    }
        active.classList.add("hover");
}

您可以在此处查看工作示例

You can see a working example here

这篇关于如何在 keydown 上使用 Javascript 模拟悬停?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆