[英]How to target the event that you click and use for offset
我有幾個div元素。 在mousedown事件中,我獲得了我單擊的元素屬性,然后使用 Jquery 偏移方法,我似乎無法正確觸發$(elt)
,因此它作為 Jquery 獲取。
我試圖盡可能少地使用 Jquery 庫作為 wan 來擺脫它。
offsetLeft和offsetTop都是在 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)
的語法,但只有當你在前面加上的ID選擇器(即ELT #
)。 有關更多信息,請參閱ID 選擇器的 jQuery 文檔。
此外, elt
被分配給id屬性,它是一個字符串。 字符串原型沒有屬性tmp 。 要設置左樣式,您可以訪問元素的樣式屬性:
e.target.style.left = e.clientX - e.target.offsetLeft;
您提到您正在“嘗試盡可能少地使用 Jquery 庫”。 我們可以刪除所有 jQuery 函數並使用原生 Javascript,如下例所示。 它使用帶有document.addEventListener() 的事件委托(請注意,舊瀏覽器的支持存在限制,例如 Internet Explorer - 請參閱MDN 文檔中有關使用 IE 添加事件處理程序的說明),檢查元素是否被點擊位於具有id屬性elementBlock的元素內(即元素本身或子元素),然后利用您提到的屬性: HTMLElement.offsetTop和HTMLElement.offsetLeft而不是 jQuery 的.position() 。
並且您可能注意到e.target.getAttribute('id')
被e.target.id
取代 - DOM 元素的屬性就足夠了。 有關這方面的更多解釋,請參閱此答案。
//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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.