鼠标悬停时显示DIV

3

mouseover 事件中,可以将该 div 附加到鼠标指针上,以便在鼠标悬停时显示其内容吗?

<div id='show' style='display:none;'></div>

如果是这样,那么应该怎么做呢?
2个回答

2
<div onmousemove="position();" onmouseout="hide();">abc</div>
<div id="tip" style="position: fixed; visibility: hidden;">that's abc!</div>
<script type="text/javascript">
  function position() {
    var d = document.getElementById('tip');
    d.style.visibility = 'visible';
    d.style.left = event.screenX + 'px';
    d.style.top = event.screenY + 'px';
  }
  function hide() {
    document.getElementById('tip').style.visibility = 'hidden';
  }
</script>

当用户将鼠标悬停在“abc” div上时,会在鼠标光标旁边显示“that's abc!”div(并跟随鼠标移动)。

k. 你能告诉我这段代码哪里出了问题吗? var ele = document.getElementById('show'); document.getElementById('show').innerHTML = el.innerHTML; ele.width ='200px'; ele.height ='30px'; ele.bgcolor ='#a9a9a9'; ele.color ='#fff'; ele.position ='absolute'; ele.display ='block'; $(window).mouseover(function(event){ $("#show").css({'top': event.pageY, 'left': event.pageX}); $('#show').height(); }); - Hulk
event.screenX + 'py' 应改为 event.screenY + 'px' - Mic
@ Hulk:那个代码的问题是它没有格式化,也无法阅读。更严重的是,“el”没有定义,而且你还混合使用了jQuery和纯JavaScript代码-你加载了jQuery吗?另外, height() 调用没有任何作用。@Mic:谢谢,已修复。 - Max Shawabkeh
你不应该使用ele.style.width、ele.style.height等吗?Hulk,请为此提出一个新问题。 - Marcel Korpel

1

试试这个:

<div id='show' onmouseover="this.style.display = 'block';"></div>

但是为了让它起作用,div 应该首先可见。然而,如果 div 被隐藏(display:none),那么 onmoueever 事件将无法找到 div,并且不会在其上触发任何事件。话虽如此,请尝试使用 visibility 属性的以下代码。

<div id='show' onmouseover="this.style.visibility = 'visible';"  onmouseout="this.style.visibility = 'hidden';"></div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接