通过 jQuery 悬停时隐藏的 div 不显示

Hidden div doesn't show on hover via jQuery

我有一个 link 并且在鼠标悬停时我想显示一个 div,全部通过 jQuery,所以要使用 currentMousePos 定位项目,但是没有任何反应。

我已经尝试声明必须获取 currentMousePos 的 div 的 class。

这里是 jQuery:

var currentMousePos = { x: -1, y: -1 };
    $(document).mousemove(function(event) {
    currentMousePos.x = event.pageX;
    currentMousePos.y = event.pageY;
    $(".hidden-img").css('top', currentMousePos.y);
    $(".hidden-img").css('left', currentMousePos.x);
});

这是CSS:

.list-item > div.hidden-img {
    display: none;
    height:300px;
    width:290px;
    margin-left:10px;
    position: absolute;
    z-index:-20;
}

.list-item > a:hover + .list-item > div.hidden-img {
    display: block; 
}

这是 HTML:

<li class="list-item">
    <a class="project-title">Text to hover</a>
     <div class="hidden-img">
      <img src='a-project-called/kremer/1.png'>
     </div>
</li>

我希望 div hidden-img 显示在 class project-title 的悬停上。

谢谢!

目前您正在通过一些相当复杂的CSS 选择器来控制hiddenDiv 的显示模式。虽然其他人可能会为您提供基于 CSS 的解决方案,但我认为更优雅的解决方案是使用 javascript 来切换显示模式。

通过调用函数在控制 html 元素的 onmouseenteronmouseout 事件中切换 hiddenDiv 的显示,您可以创建您正在寻找的悬停行为:

//takes in an ID, finds element using that ID, then toggles that
//  element's display between block and none
function toggleHiddenDisplay(id){
  elem = document.getElementById(id)
  if(elem.style.display == 'none'){
    elem.style.display = 'block';
  }else elem.style.display = 'none';
}
<html>
  <div>
    <a onmouseenter=toggleHiddenDisplay('hiddenDiv')
       onmouseout=toggleHiddenDisplay('hiddenDiv')>
       Text to Hover
    </a>
    <div id="hiddenDiv" 
       style="color:white; background-color:red; display:none;">
       Hidden Content
    </div>
  </div>
</html>

所以现在你有两个组件:

  1. Javascript/html-event 基于悬停时切换显示模式的设置
  2. Jquery 根据当前光标位置设置元素位置的脚本。

这两个可以集成在一起,为您提供所需的组合切换+显示鼠标行为:

var currentMousePos = { x: -1, y: -1 };
    $(document).mousemove(function(event) {
    currentMousePos.x = event.pageX;
    currentMousePos.y = event.pageY;
    $(".hidden-img").css('top', currentMousePos.y);
    $(".hidden-img").css('left', currentMousePos.x);
});

function toggleHiddenDisplay(id){
  elem = document.getElementById(id)
  if(elem.style.display == 'none'){
    elem.style.display = 'block';
  }else elem.style.display = 'none';
}
.list-item > div.hidden-img {
    display: none;
    height:300px;
    width:290px;
    margin-left:10px;
    position: absolute;
    z-index:-20;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="list-item">
    <a class="project-title" onmouseenter=toggleHiddenDisplay("hoverDisplay") onmouseout=toggleHiddenDisplay("hoverDisplay")>Text to hover</a>
     <div class="hidden-img" id="hoverDisplay" style="display:none;">
      <img src='https://www.gravatar.com/avatar/fe56d599fb9eeafdde6be4b369d51512?s=328&d=identicon&r=PG&f=1'>
     </div>
</li>