首页 > 解决方案 > 使用“onmouseover”创建一个简单的下拉菜单

问题描述

嗨,当我将鼠标悬停在一个元素上时,我只想要一个小框下拉,当我鼠标移出时我希望它消失。我哪里错了?

我的 HTML:

 <div onmouseover = 'mouseOverToggle()' onmouseout = '//function' id = 'new' class = 'child new'> New
     <div  id ='newDropDown' class="new dropdown"><a href=""></a></div> 
 </div>

Javascript:

var newDropdown = document.getElementById('new');
var dropDownContent = document.getElementById('newDropDown');

dropDownContent.style.display = 'none'

newDropdown.addEventListener('mouseover', mouseOverToggle);

function mouseOverToggle() {
   dropDownContent.style.display === 'none' ? 'show' : 'none' 
}

标签: javascriptonmouseoverboxdrop

解决方案


我更改了您的代码中的几处。但是,这有效:

var dropDownContent = document.getElementById('newDropDown');
dropDownContent.style.display = 'none';
function mouseOverToggle() {
   dropDownContent.style.display = "";
}
function mouseOutToggle() {
   dropDownContent.style.display = "none";
}
 <div onmouseover='mouseOverToggle()' onmouseout='mouseOutToggle()' id='new' class='child new'>Mouse over this!
   <div id='newDropDown' class="new dropdown">
     <a href="#">First option</a>
   </div>
 </div>

不过,你问你哪里出错了,所以这里是实际上阻止它工作的东西:

  • 标签是空的<a>,所以你看不到它。
  • 有几个分号丢失。
  • 而不是===(在精确比较时使用),用于=将某些内容分配给属性/变量。
  • 三元组不起作用,因为'none'无法判断您是否将鼠标悬停在它上面;它只是字符串none

(其余不需要的东西我不会提及,但我确实删除了它。)


推荐阅读