javascript - 使用“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'
}
解决方案
我更改了您的代码中的几处。但是,这有效:
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
。
(其余不需要的东西我不会提及,但我确实删除了它。)
推荐阅读
- javascript - 当 DOM style="display:block; 使用 selenium/js 时,有什么方法可以获取元素的文本
- crystal-reports - Crystal Report - 将页脚抑制到最后一页 - 在其他页面上创建空白区域
- python - Python/Flask:有没有办法生成密码提示而不是制作整个用户平台?
- python - Unity POST 到本地主机的请求
- sql - 索引是否会影响 where is not null 查询的性能?
- react-native - undefined 不是对象(评估 '_expo.default.Localization.locale')
- python - IBM 语音转文本用户名和密码问题
- javascript - XMLHttpRequest:如何导航“链接”标头
- spring - 使用 Spring 配置从 Spring 连接到 WebSphere MQ
- python - 无法解决 LinAlgError:数组的最后 2 个维度必须是正方形