javascript 鼠标悬停在div上弹出消息

yduiuuwa  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(154)

尝试在mouseover a div上显示一个简单的弹出窗口,我按照答案Description Box using "onmouseover"操作,但不起作用。我错过了什么?

<!DOCTYPE html>
<head>
<style>
    .parent .popup {
      display: none;
    }
    .parent:hover .popup {
      display: block;
    }
</style>
</head>

<body>
<script type="text/javascript">
    var e = document.getElementById('#parent');
    e.onmouseover = function() {
      document.getElementById('popup').style.display = 'block';
    }
    e.onmouseout = function() {
      document.getElementById('popup').style.display = 'none';
    }
</script>

<div id="parent">
    This is the main container.
    <div id="popup" style="display: none">some text here</div>
</div>

</body> 
</html>
jdg4fx2g

jdg4fx2g1#

有几个问题。你在CSS中引用类(.是class,#是id),第二,你不需要重载CSS display none样式。最后,在这种情况下,你不需要JavaScript。
参见工作示例。

<!DOCTYPE html>
<head>
<style>
    #parent #popup {
      display: none;
    }
    #parent:hover #popup {
      display: block;
    }
</style>
</head>

<body>


<div id="parent">
    This is the main container.
    <div id="popup">some text here</div>
</div>

</body> 
</html>
lf5gs5x2

lf5gs5x22#

如果弹出窗口在外部(而不是在父窗口内部),则:

#popup {
  display: none;
}

#sibling:hover+#popup {
  display: block;
}
<div id="sibling">
  This is the main container.
</div>
<div id="popup">some text here</div>

相关问题