javascript - 鼠标悬停时如何获取td,div标签的id

标签 javascript jquery html

这里我有一个表格,每行第一个单元格包含一个 Div,它可以向右扩展, 这里的 div 位于第一个单元格 id(R1Date1) 中,当我将其扩展到第二个单元格时,我需要提醒第二个单元格 id (R1Date2) 和 Div Id(Book1) 下面是我尝试过的代码,但它无法正常工作,因为我对 Jquery 事件不太熟悉

window.console = window.console || function(t) {};
if (document.location.search.match(/type=embed/gi)) {
  window.parent.postMessage("resize", "*");
}
window.onload = function() {
  initDragElement();
  initResizeElement();
};

function initDragElement() {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  var popups = document.getElementsByClassName("popup");
  var elmnt = null;
  var currentZIndex = 100; //TODO reset z index when a threshold is passed

  for (var i = 0; i < popups.length; i++) {
    if (window.CP.shouldStopExecution(0)) break;
    var popup = popups[i];
    var header = getHeader(popup);

    popup.onmousedown = function() {
      this.style.zIndex = "" + ++currentZIndex;
    };

    if (header) {
      header.parentPopup = popup;
      header.onmousedown = dragMouseDown;
    }
  }
  window.CP.exitedLoop(0);

  function dragMouseDown(e) {
    elmnt = this.parentPopup;
    elmnt.style.zIndex = "" + ++currentZIndex;

    e = e || window.event;
    // 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) {
    if (!elmnt) {
      return;
    }

    e = e || window.event;
    // 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;
  }

  function getHeader(element) {
    var headerItems = element.getElementsByClassName("popup-header");

    if (headerItems.length === 1) {
      return headerItems[0];
    }

    return null;
  }
}

function initResizeElement() {
  var popups = document.getElementsByClassName("popup");
  var element = null;
  var startX, startY, startWidth, startHeight;

  for (var i = 0; i < popups.length; i++) {
    if (window.CP.shouldStopExecution(1)) break;
    var p = popups[i];

    var right = document.createElement("div");
    right.className = "resizer-right";
    p.appendChild(right);
    right.addEventListener("mousedown", initDrag, false);
    right.parentPopup = p;

    var bottom = document.createElement("div");
    bottom.className = "resizer-bottom";
    p.appendChild(bottom);
    bottom.addEventListener("mousedown", initDrag, false);
    bottom.parentPopup = p;

    var both = document.createElement("div");
    both.className = "resizer-both";
    p.appendChild(both);
    both.addEventListener("mousedown", initDrag, false);
    both.parentPopup = p;
  }
  window.CP.exitedLoop(1);

  function initDrag(e) {
    element = this.parentPopup;

    startX = e.clientX;
    startY = e.clientY;
    startWidth = parseInt(
      document.defaultView.getComputedStyle(element).width, 10);

    startHeight = parseInt(
      document.defaultView.getComputedStyle(element).height, 10);

    document.documentElement.addEventListener("mousemove", doDrag, false);
    document.documentElement.addEventListener("mouseup", stopDrag, false);
  }

  function doDrag(e) {
    element.style.width = startWidth + e.clientX - startX + "px";
    // element.style.height = startHeight + e.clientY - startY + "px";
  }

  function stopDrag(e) {
    alert(e.target.id);
    document.documentElement.removeEventListener("mousemove", doDrag, false);
    document.documentElement.removeEventListener("mouseup", stopDrag, false);
  }
}

$(window).load(function() {

  $(document).on("mouseup", ".mybox", function(event) {
    if (event.target === this) {
      alert($(this).attr("id"));
    }
  });

});
tr {
  height: 50px;
}

td {
  position: relative;
}

.popup {
  z-index: 9;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  text-align: center;
  /* min-height: 150px;
    min-width: 300px;
    max-height: 300px;
    max-width: 600px;*/
}


/*Drgable */

.popup {
  position: absolute;
  /*resize: both; !*enable this to css resize*! */
  overflow: auto;
}

.popup-header {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196f3;
  color: #fff;
}

.popup-header_No {
  z-index: 10;
  background-color: #2196f3;
  color: #fff;
}


/*Resizeable*/

.popup .resizer-right {
  width: 5px;
  height: 100%;
  background: transparent;
  position: absolute;
  right: 0;
  bottom: 0;
  cursor: e-resize;
}


/*
    .popup .resizer-bottom {
      width: 100%;
     height: 5px;
     background: transparent;
      position: absolute;
      right: 0;
      bottom: 0;
      cursor: n-resize;
    }

    .popup .resizer-both {
     width: 5px;
      height: 5px;
      background: transparent;
      z-index: 10;
      position: absolute;
      right: 0;
      bottom: 0;
      cursor: nw-resize;
    }*/


/*NOSELECT*/

.popup * {
  -webkit-touch-callout: none;
  /* iOS Safari */
  -webkit-user-select: none;
  /* Safari */
  -khtml-user-select: none;
  /* Konqueror HTML */
  -moz-user-select: none;
  /* Firefox */
  -ms-user-select: none;
  /* Internet Explorer/Edge */
  user-select: none;
  /* Non-prefixed version, currently
                                      supported by Chrome and Opera */
}
<html lang="en">

<head>
  <meta charset="UTF-8">
  <style>

  </style>
  <script>
  </script>
</head>

<body>
  <table border="1" style="width:100%">
    <tr>
      <td id="R1Date1" class="mybox">
        <div class="popup" id='Book1'>
          <div class="popup-header_No">Click here to move</div>
        </div>
      </td>
      <td id='R1Date2'></td>
    </tr>

    <tr>
      <td id="R2Date1">
        <div class="popup" id='Book2'>
          <div class="popup-header_No">Click here to move</div>
        </div>
      </td>
      <td id="R2Date2"></td>
    </tr>

  </table>


  <script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
  <script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
  

最佳答案

如果我理解得很好,您要做的就是在完成拖动时获取鼠标下的元素。

您可以使用函数 document.elementFromPoint(x, y);

检索它

这里获取鼠标下所有重叠的元素是一个很有用的功能。

function getAllElementsFromPoint(x, y) {
    var elements = [];
    var visibility = [];
    var item = document.elementFromPoint(x, y);
    while (item && item !== document.body && item !== window && item !== document && item !== document.documentElement) {
        elements.push(item);
        visibility.push(item.style.visibility);
        item.style.visibility = "hidden";
        item = document.elementFromPoint(x, y);
    }
    // restore display property
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.visibility = visibility[i];
    }
    return elements;
}

一旦获得它们,您只需从返回的数组中获取适合您的第一个元素即可。

这是完整的示例。

window.console = window.console || function(t) {};
if (document.location.search.match(/type=embed/gi)) {
  window.parent.postMessage("resize", "*");
}
window.onload = function() {
  initDragElement();
  initResizeElement();
};

function initDragElement() {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  var popups = document.getElementsByClassName("popup");
  var elmnt = null;
  var currentZIndex = 100; //TODO reset z index when a threshold is passed

  for (var i = 0; i < popups.length; i++) {
    if (window.CP.shouldStopExecution(0)) break;
    var popup = popups[i];
    var header = getHeader(popup);

    popup.onmousedown = function() {
      this.style.zIndex = "" + ++currentZIndex;
    };

    if (header) {
      header.parentPopup = popup;
      header.onmousedown = dragMouseDown;
    }
  }
  window.CP.exitedLoop(0);

  function dragMouseDown(e) {
    elmnt = this.parentPopup;
    elmnt.style.zIndex = "" + ++currentZIndex;

    e = e || window.event;
    // 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) {
    if (!elmnt) {
      return;
    }

    e = e || window.event;
    // 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;
  }

  function getHeader(element) {
    var headerItems = element.getElementsByClassName("popup-header");

    if (headerItems.length === 1) {
      return headerItems[0];
    }

    return null;
  }
}

function getAllElementsFromPoint(x, y) {
    var elements = [];
    var visibility = [];
    var item = document.elementFromPoint(x, y);
    while (item && item !== document.body && item !== window && item !== document && item !== document.documentElement) {
        elements.push(item);
        visibility.push(item.style.visibility);
        item.style.visibility = "hidden";
        item = document.elementFromPoint(x, y);
    }
    // restore display property
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.visibility = visibility[i];
    }
    return elements;
}

function initResizeElement() {
  var popups = document.getElementsByClassName("popup");
  var element = null;
  var startX, startY, startWidth, startHeight;

  for (var i = 0; i < popups.length; i++) {
    if (window.CP.shouldStopExecution(1)) break;
    var p = popups[i];

    var right = document.createElement("div");
    right.className = "resizer-right";
    p.appendChild(right);
    right.addEventListener("mousedown", initDrag, false);
    right.parentPopup = p;

    var bottom = document.createElement("div");
    bottom.className = "resizer-bottom";
    p.appendChild(bottom);
    bottom.addEventListener("mousedown", initDrag, false);
    bottom.parentPopup = p;

    var both = document.createElement("div");
    both.className = "resizer-both";
    p.appendChild(both);
    both.addEventListener("mousedown", initDrag, false);
    both.parentPopup = p;
  }
  window.CP.exitedLoop(1);

  function initDrag(e) {
    element = this.parentPopup;

    startX = e.clientX;
    startY = e.clientY;
    startWidth = parseInt(
      document.defaultView.getComputedStyle(element).width, 10);

    startHeight = parseInt(
      document.defaultView.getComputedStyle(element).height, 10);

    document.documentElement.addEventListener("mousemove", doDrag, false);
    document.documentElement.addEventListener("mouseup", stopDrag, false);
  }

  function doDrag(e) {
    element.style.width = startWidth + e.clientX - startX + "px";
    // element.style.height = startHeight + e.clientY - startY + "px";
  }

  function stopDrag(e) {
  
    let x = e.clientX;
    let y = e.clientY;
    let elementsUderTheMouse = getAllElementsFromPoint(x, y);
    let tdUnderTheMouse = elementsUderTheMouse.find(function(element) {
      return element.tagName === "TD";
    });
    console.log(elementsUderTheMouse);
    alert(tdUnderTheMouse.id);
    
    document.documentElement.removeEventListener("mousemove", doDrag, false);
    document.documentElement.removeEventListener("mouseup", stopDrag, false);
  }
}

$(window).load(function() {

  $(document).on("mouseup", ".mybox", function(event) {
    if (event.target === this) {
      alert($(this).attr("id"));
    }
  });

});
tr {
  height: 50px;
}

td {
  position: relative;
}

.popup {
  z-index: 9;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  text-align: center;
  /* min-height: 150px;
    min-width: 300px;
    max-height: 300px;
    max-width: 600px;*/
}


/*Drgable */

.popup {
  position: absolute;
  /*resize: both; !*enable this to css resize*! */
  overflow: auto;
}

.popup-header {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196f3;
  color: #fff;
}

.popup-header_No {
  z-index: 10;
  background-color: #2196f3;
  color: #fff;
}


/*Resizeable*/

.popup .resizer-right {
  width: 5px;
  height: 100%;
  background: transparent;
  position: absolute;
  right: 0;
  bottom: 0;
  cursor: e-resize;
}


/*
    .popup .resizer-bottom {
      width: 100%;
     height: 5px;
     background: transparent;
      position: absolute;
      right: 0;
      bottom: 0;
      cursor: n-resize;
    }

    .popup .resizer-both {
     width: 5px;
      height: 5px;
      background: transparent;
      z-index: 10;
      position: absolute;
      right: 0;
      bottom: 0;
      cursor: nw-resize;
    }*/


/*NOSELECT*/

.popup * {
  -webkit-touch-callout: none;
  /* iOS Safari */
  -webkit-user-select: none;
  /* Safari */
  -khtml-user-select: none;
  /* Konqueror HTML */
  -moz-user-select: none;
  /* Firefox */
  -ms-user-select: none;
  /* Internet Explorer/Edge */
  user-select: none;
  /* Non-prefixed version, currently
                                      supported by Chrome and Opera */
}
<html lang="en">

<head>
  <meta charset="UTF-8">
  <style>

  </style>
  <script>
  </script>
</head>

<body>
  <table border="1" style="width:100%">
    <tr>
      <td id="R1Date1" class="mybox">
        <div class="popup" id='Book1'>
          <div class="popup-header_No">Click here to move</div>
        </div>
      </td>
      <td id='R1Date2'></td>
    </tr>

    <tr>
      <td id="R2Date1">
        <div class="popup" id='Book2'>
          <div class="popup-header_No">Click here to move</div>
        </div>
      </td>
      <td id="R2Date2"></td>
    </tr>

  </table>


  <script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
  <script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>

关于javascript - 鼠标悬停时如何获取td,div标签的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57722382/

相关文章:

javascript - Parse - Javascript 嵌套调用

javascript - 如何更改 src 的一部分并将其插入数组?

html - 使用 Typescript 变量创建 img src

javascript - JQuery IF 文档 url = "../products.html"然后执行此操作

javascript - silverlight 控件加载完成后如何调用 javascript 函数?

Javascript 排序功能无法正常运行

javascript - 重新出现动画完成后元素消失

html - 无法运行简单的 polymer 应用程序

php - 从 WordPress 获取最后 5 个帖子标题及其缩略图

javascript - 执行 npm 时自动添加包