我正在为家庭作业构建一个网页。我想弄清楚每当我将鼠标悬停在底部的父 div 上时如何使子 div 出现,有点像下拉菜单。问题是子 div 有一个类,我只想要悬停的元素显示父 div 中的子 div。更具体地说,我所说的父 div 是 <div class="inside-box" onMouseOver="showDDContent();" onMouseOut="hideDDContent();>
我说的子 div 是 <div class="dropdown-content">
.我想使用 Vanilla Javascript(首选)或 CSS(非首选)。
TLDR:如何在 Vanilla Javascript 中仅定位来自 HTML/CSS 类的当前悬停元素?
我该怎么做?
我做到了这一点:
HTML
<!--Lab 1-->
<!--Each individual box.-->
<div class="box">
<!--The box inside each individual box. Think of it as like bubble wrap inside a box.-->
<div class="inside-box" onMouseOver="showDDContent();" onMouseOut="hideDDContent();">
<!--The div with an image in it. Top one inside the box div.-->
<div>
<a href="Lab_01/LB1_WeiJianZhen_DD.html">
<!--Get an image with 300px width by 200px height. Make it responsive.-->
<img src="../../../Visual Content/placeholder.jpg" alt="Under Contruction" class="imgGrids">
</a>
</div>
<!--The div that contains the heading or title of the lab.-->
<div class="txtBar">
<h3><a href="Lab_01/LB1_WeiJianZhen_DD.html">Lab 1</a></h3>
</div>
<!--The div that drops down to explain the lab with some text.-->
<div class="dropdown-content">
<p>My first website ever made in an HTML file! Describes a bit about the process of making a very basic website like mine.</p>
</div>
<!--End of inside box div.-->
</div>
<!--End of box div.-->
</div>
CSS
/*Creates the styling of the dropdown box.*/
.dropdown-content {
display: none;
position: relative;
background-color: #62ff36;
box-shadow: 0px 8px 16px 0px rgba(56, 255, 42, 0.8);
padding: 12px 0px;
z-index: 1;
}
JavaScript
function showDDContent() {
document.getElementsByClassName("dropdown-content").style.display = "block";
}
function hideDDContent() {
document.getElementsByClassName("dropdown-content").style.display = "none";
}
最佳答案
显然,解决此问题的最简单、最高效且总体上绝对最好的方法是使用 CSS。
.inside-box:hover .dropdown-content { display: block; }
如果出于某种原因您坚持使用 Javascript(我明确不推荐),您将不得不为每个 添加 2 个监听器。 inside-box
,一个用于mouseenter
,另一个用于mouseleave
:
document.querySelectorAll('.inside-box').forEach(insideBox => {
insideBox.addEventListener('mouseenter', () => insideBox.querySelector('.dropdown-content').style.display = 'block');
insideBox.addEventListener('mouseleave', () => insideBox.querySelector('.dropdown-content').style.display = 'none');
})
像您建议的那样使用内联事件监听器被认为是非常糟糕的做法,所以不要尝试。
关于javascript - 如何仅针对 Vanilla Javascript 中的当前悬停元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684879/