微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

悬停父元素时如何在子元素上应用CSS?

如何解决悬停父元素时如何在子元素上应用CSS?

我正在研究纯 javascript 可拖动和相当大的 div。一切都很好,但我只有一个问题,那就是当我将鼠标悬停在父 div 上时,我需要显示只是一个子 div 的句柄。

您可以简单地删除并阅读 .onHover {display: none;} 以查看目标 div。 您可以在此 link

中找到相关示例

HTML

<div id="DraggableImage">
  <div id="DraggableImageHandle" class="onHover">move</div>
</div>

CSS

    #DraggableImage {
      position: absolute;
      z-index: 9;
      background-color: #f1f1f1;
      text-align: center;
      border: 1px solid #d3d3d3;
      overflow: hidden;
      resize: both;
      width: 500px;
      height: 300px;
      
      background-image: url("https://media-exp3.licdn.com/dms/image/C560BAQHMG7ReC3Layw/company-logo_200_200/0/1519874455151?e=2159024400&v=beta&t=FYZf0Jr4bhHIaWgGlQ8wTYVU4phKbinvvvcnNGRVGHA");
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
    }
    
    #DraggableImageHandle {
      padding: 10px;
      cursor: move;
      z-index: 10;
      background-color: blueviolet;
      color: #fff;
      position: absolute;
      top:calc(50% - 35px);
      left: calc(50% - 50px);
      height: 50px;
      width: 80px;
    }
    
    
    .onHover {
      display: none;
    }
    
    #DraggableImage:hover + .onHover{
      display: block;
    }

JavaScript

//Make the DIV element draggagle:
dragElement(document.getElementById("DraggableImage"));

function dragElement(elmnt) {
  var pos1 = 0,pos2 = 0,pos3 = 0,pos4 = 0;
  if (document.getElementById(elmnt.id + "Handle")) {
    /* if present,the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "Handle").onmousedown = dragMouseDown;
  } else {
    /* otherwise,move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

解决方法

删除 +

 #DraggableImage:hover .onHover{
      display: block;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。