如何定位您单击并用于偏移的事件

How to target the event that you click and use for offset

我有几个 div 元素。在 mousedown 事件中,我得到了我点击的元素属性,然后使用 Jquery 偏移方法, 我似乎无法正确触发 $(elt),因此它显示为 Jquery。

我正在尝试尽可能少地使用 Jquery 库来摆脱它。

offsetLeftoffsetTop 都是在 HTML 元素上定义的 JavaScript 属性。 offset() 是一个需要 jQuery 对象的 jQuery 方法。 我知道你只需要像这样包装元素 $(elt).

我在关闭标签之前在 JS 的最后一行遇到错误。

 elementBlock.on('mousedown',function(e){
        var el = e.target.nodeName;
        var elt = e.target.getAttribute('id');
        console.log(elt); // i get the clean attribute
        console.log(el); // i get DIV
        elt.tmp.left = e.clientX - $(elt).offset().left;

}

HTML

 <div  id="elementBlock">
                  <div id="blue-left"></div>
                  <div id="blue-right"></div>
                </div>

您想使用 $(e.target) 而不是 $(elt)

您当前代码中的问题是,如果您想通过 ID 定位 jQuery 元素,您需要在该选择器前加上 #.

前缀

所以 $("#" + elt) 也可以,但他们上面的建议更清晰。有关 jQuery 选择器的更多信息,请参见此处:https://api.jquery.com/category/selectors/

是的,您可以使用 $(elt) 语法,但前提是您在 elt 前面加上 ID 选择器(即 #)。有关详细信息,请参阅 ID Selector 的 jQuery 文档。

此外,elt 被分配给 id 属性,它是一个字符串。 string prototype 没有 属性 tmp。要设置样式 left,您可以访问元素的 style 属性:

e.target.style.left = e.clientX - e.target.offsetLeft;

编辑:

您提到您“尝试尽可能少地使用 Jquery 库 ”。我们可以删除所有 jQuery 函数并使用原生 Javascript,如下例所示。它使用 document.addEventListener() (Note that there are limitations with support by older browsers, such as Internet Explorer- see the notes about adding event handlers with IE in the MDN documentation), checks to see if the element clicked on is within the element with id attribute elementBlock (i.e. the element itself or a child element), and then utilizes the properties you mentioned: HTMLElement.offsetTop and HTMLElement.offsetLeft instead of jQuery's .position() 的事件委托。

您可能注意到 e.target.getAttribute('id') 的用法已被 e.target.id 取代 - DOM 元素的 属性 就足够了。有关这方面的更多解释,请参阅 this answer.

//observe DOM ready
document.addEventListener('DOMContentLoaded', function() {
  //observe clicks on the DOM
  document.addEventListener('click', function(clickEvent) {
    //look up the DOM tree from the event target to see if we clicked within the elementBlock container
    var target = clickEvent.target;
    while (target && target.id !== 'elementBlock' && target !== undefined) {
      target = target.parentNode;
    }
    //if we clicked within the elementBlock container
    if (target && target.id == 'elementBlock') {
      //log out the offsetTop and offsetLeft
      console.log('offsetTop: ', clickEvent.target.offsetTop);
      console.log('offsetLeft: ', clickEvent.target.offsetLeft);
    }
  });
});
#container div {
  border: 1px solid #000;
  padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="elementBlock">elementBlock
    <div id="blue-left">L</div>
    <div id="blue-right">R</div>
  </div>
</div>