使用JavaScript在悬停时添加类

使用JavaScript在悬停时添加类,javascript,css,html,sass,Javascript,Css,Html,Sass,我想在ul上添加一个类,它位于nav中的一个li元素中。我的问题是,我想在鼠标悬停时显示列表,然后在上面单击某个内容,但当我用鼠标输入时,会显示li菜单,当我想向下单击某个内容时,菜单就会消失。我想在香草JavaScript中实现这一点 document.addEventListener('DOMContentLoaded',函数(){ var dropdownItem=document.querySelector('.dropdownItem'); var dropdown=document

我想在ul上添加一个类,它位于nav中的一个li元素中。我的问题是,我想在鼠标悬停时显示列表,然后在上面单击某个内容,但当我用鼠标输入时,会显示li菜单,当我想向下单击某个内容时,菜单就会消失。我想在香草JavaScript中实现这一点

document.addEventListener('DOMContentLoaded',函数(){
var dropdownItem=document.querySelector('.dropdownItem');
var dropdown=document.querySelector('.dropdown');
dropdownItem.addEventListener('mouseenter',函数(e){
dropdown.classList.add('dropdown-show');
});
addEventListener('mouseleave',函数(){
dropdown.classList.remove('dropdown-show');
})
})
菜单{
列表样式:无;
显示器:flex;
宽度:30%;
证明内容:之间的空间;
对齐项目:居中;
}
李先生{
位置:相对位置;
}
.菜单李a{
颜色:#999;
文字装饰:无;
}
.菜单.下拉项{
位置:相对位置;
}
.菜单.下拉菜单项.下拉菜单{
位置:绝对位置;
列表样式:无;
顶部:5px;
填充顶部:40px;
左:-30px;
可见性:隐藏;
不透明度:0;
过渡:0.3s;
}
.菜单.下拉项.下拉.三角形{
边框:10px实心透明;
边框底色:#000;
宽度:0;
顶部:20px;
左:50%;
转化:translateX(-50%);
位置:绝对位置;
}
.菜单.下拉项.下拉.下拉显示{
不透明度:1;
能见度:可见;
}
.菜单.下拉项.下拉列表{
背景色:#000;
填充:10px 20px;
字体重量:较轻;
}

您可以使用以下内容:

<ul class="dropdown" onmouseover="hoverTrue($event)" onmouseout="hoverOut($event)">

function hoverTrue(event) {
 event.target.style.display = 'block'; 
 //or add class
 event.target.setAttribute('class', 'something');
}

function hoverOut(event) {
 event.target.style.display = 'none';
 //or add class
 event.target.setAttribute('class', 'something');
}
    函数hoverTrue(事件){ event.target.style.display='block'; //或者添加类 event.target.setAttribute('class','something'); } 函数悬停(事件){ event.target.style.display='none'; //或者添加类 event.target.setAttribute('class','something'); }
我的li的默认Z索引不知何故位于其他分区下

.menu {
    list-style: none;
    display: flex;
    width: 30%;
    justify-content: space-between;
    align-items: center;
    z-index: 999;
}
现在它工作得很好,菜单上的mouseleave并没有消失


感谢大家的帮助

使用“mouseover”事件而不是“mouseenter”,使用“mouseout”而不是“mouseleave”。

您的SCS发生了很多事情,在JSFIDLE中不起作用。这就是说,我能够通过这个小片段获得您想要的基本功能

代码的问题是,您正在将
mouseleave
事件添加到最开始显示下拉列表的元素(下拉项)中。
mouseleave
事件应位于父级(下拉菜单)上

代码如下:

document.getElementsByCassName(“下拉项”)[0]。addEventListener(“鼠标悬停”,函数(e){
const parent=e.target.parentElement;
if(parent&&parent.tagName==“LI”&&parent.classList.contains(“下拉项”)){
const parent=e.target.parentElement;
parent.children[1].classList.add(“活动”);
}
});
document.getElementsByClassName(“下拉列表”)[0]。addEventListener(“鼠标输出”,函数(e){
e、 target.classList.remove(“活动”);
});
。下拉列表{
显示:无;
}
.主动{
显示:块;
}

为什么不使用css呢?如果你只是想显示/隐藏东西,你可能完全可以使用css来完成这项工作。@DomenikReitzner我知道如何在css中完成这项工作,但我需要用JS来完成,我的意思是有人想要:)你能将它更改为包含常规css以便它可以在代码段中运行吗?不,你找到了,所以没有人应该添加它。你自己添加。当你想使用过渡时,你不能改变你的风格display@Freestyle09您可以使用
不透明度
指针事件:无
这不相关。OP的代码实际上是有效的(不需要简单地使用内联处理程序,而内联处理程序不会改变任何东西)。使用
setAttribute
在元素上设置类比在鼠标悬停事件中使用.write console.log('hi')要麻烦得多(它会清除元素上现有的类),你会看到为什么不这样做