gpt4 book ai didi

javascript - JQuery:在 dragstart 事件上更改 DOM 会立即触发 dragend?

转载 作者:可可西里 更新时间:2023-11-01 01:18:29 25 4
gpt4 key购买 nike

我遇到了 Chrome 和 Opera 的错误,我想知道它是否已知,如果已知,是否有解决方案?

如果我在 dragstart 事件上更改 DOM,它会立即触发 dragend 事件?!这是一个错误还是背后有什么原因?只发生在 Chrome 和 Opera 中。 Firefox 有效。

我感谢每一个答案。

$('body').on({
dragstart: function(e) {

dragProfilefieldSrcElformid = $(this).attr("data-profilefieldid-formid");
e.dataTransfer = e.originalEvent.dataTransfer;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', $(this).attr("data-profilefieldid"));

// Changing the DOM, fires the dragend Event in Chrome?
$("#plugin_loginlogout_pfcontainer_" + dragProfilefieldSrcElformid).find(".plugin_loginlogout_pf_entryfield").addClass("highlight"); // This doesn't work in Chrome and Opera, but in Firefox
},
dragend: function() {
console.log("dragend");
}
".plugin_loginlogout_pf");

编辑:

将 DOM 更改放在 setTimeout 函数中似乎可以解决问题!

最佳答案

似乎不同的浏览器对长时间运行的操作表现出不同的行为。

JavaScript 有一个单独的线程,它运行同一个队列中的所有指令。每个队列项目按顺序运行,一旦项目完成执行,下一个项目(来自队列)被抓取并运行。

长时间运行操作的罪魁祸首是您尝试对 DOM 进行的更改(我假设在使用 find() 进行大量搜索之前,它将运行 DOM 操作每个匹配的元素)。

What happens as you drag the element is that, all lines of code in the dragstart handler, and as you stop dragging, the dragend handler are pushed to the message queue respectively in order to be executed serially. However the DOM manipulation is taking more time (probably a few milliseconds more) to execute than the execution of the dragend handler before you stop dragging, and therefore, it appears as if the dragend fired way too soon.

注意:有时代码块创建一个新事件,因此被推到浏览器事件队列的末尾( 或者可能在正在运行的项目之后的某处),导致稍后执行。 (我想它的性质因浏览器而异。)

您的代码的 DOM 操作部分可能在 Chrome 和 Opera 中面临这样的问题,但我不确定。

setTimeout(fn, 0) 技巧

此类情况的解决方法是将长时间运行的操作 block 包装setTimeout 函数中,时间为 0

(您可以将此视为告诉浏览器运行您的代码部分,一点时间都没有!,而不是虽然字面意思。)

一旦一段代码执行完毕,浏览器会搜索等待运行的可用项目,带有setTimeoutsetInterval 的将被推送到在第一个可用时刻排队。

在您的特定情况下,诀窍是 setTimeout 延迟 DOM 更改的执行到稍后的时间(至少 0 seconds) 而不是 dragend 事件处理程序,因此给人的印象就好像 dragend 事件是在 DOM 更改后触发的。

@DVK 发表了一篇很棒的文章 here解释为什么 setTimeout(fn, 0) 有时很有用。请检查 JSfiddle他(在 Chrome 中)也是如此。

更新

正如@MojoJojo 和@Pradeep 所指出的,似乎 Webkit 浏览器(尤其是旧版 Chrome)在 drag 事件方面存在问题。但是,我尝试在 Chrome 版本 47.0.2526.106(截至 2016 年 1 月 11 日的最新版本)中重现该错误,并且 drag 事件触发时没有任何异常。

无论如何,即使存在错误,setTimeout 技巧仍然适用作为该问题的适当解决方法。

关于javascript - JQuery:在 dragstart 事件上更改 DOM 会立即触发 dragend?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com