如何仅以Vanilla Javascript为目标当前悬停的元素

我正在构建用于作业的网页。我想弄清楚每当我将鼠标悬停在底部的父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";
}
cao2826 回答:如何仅以Vanilla Javascript为目标当前悬停的元素

使用 CSS 可以最轻松,最有效,整体上肯定是解决此问题的最佳方法。

.inside-box:hover .dropdown-content { display: block; }

如果出于任何原因您坚持使用 Javascript (我明确建议不推荐),则您将不得不向每个{{1} },一个用于.inside-box,另一个用于mouseenter

mouseleave

使用您建议的内联事件侦听器被认为是非常不好的做法,因此请不要尝试。

本文链接:https://www.f2er.com/3170030.html

大家都在问