双击事件函数 JavaScript

huangapple go评论64阅读模式
英文:

Double click event function javascript

问题

In the second click on the element, I need it to make highlight first, then the next click will delete it from the DOM, but it deletes directly without highlighting first.

在第二次点击元素时,我希望它先突出显示,然后在下一次点击时从DOM中删除,但它直接删除而不先突出显示。

英文:

the function working well,
but when I click on first element and second element then first once again,
He skips the highlight and moves to the second event, remove direct.

HTML

<button class="cancelBtn">Cancel highlighting</button>
	<div>
		<a href="#" class="btn">Button</a>
		<a href="#" class="btn">Button</a>
		<a href="#" class="btn">Button</a>
		<a href="#" class="btn">Button</a>
		<a href="#" class="btn">Button</a>
		<a href="#" class="btn">Button</a>
	</div>
	<style>
		.btn.click {
			background-color: red;
		}
	</style>

JS

function doubleClickEvenElements(eventElements, cancelHighlightingElement) {
  eventElements.forEach(eventElement => {

    let count = 0;

    eventElement.addEventListener("click", element => {

      element.target.classList.add("element");
      eventElements.forEach(ele => {ele.classList.remove("click");});
      element.target.classList.add("click");

      count++;

      if (count == 2) {

        element.target.remove();
        count = 0;

      };

    });

    cancelHighlightingElement.addEventListener("click", btn => {

      count = 0;
      eventElements.forEach(ele => {ele.classList.remove("click");});

    });

  });

};

let eventElements = document.querySelectorAll("div .btn");
let cancelHighlighting = document.querySelector(".cancelBtn");

doubleClickEvenElements(eventElements, cancelHighlighting);

you can try the code on CodePen

in the second click on the element, I need it to make highlight first then next click will delete it from DOM, but it deletes direct without highlight first.

I'm sorry about my bad explain, I hope you are understanding what I'm saying 😺.

答案1

得分: 1

在一般情况下,我建议不要计算点击次数以检查双击,因为这也会适用于非常缓慢的双击或者(比如你的例子)先点击元素A,然后是B,再是A。

我建议检查“最后一次点击”的时间,如果超过了,比如说,500毫秒,就不要将这次点击视为(第二次)双击。

以下是一个示例,使用500毫秒作为阈值:

myDoubleClickElement.addEventListener('click', (e) => {
    if (new Date().getTime() - (e.target._lastTouch || 0) > 500) {
        e.target._lastTouch = new Date().getTime();
        e.preventDefault(); //不允许操作继续进行
    } else {
        //允许操作继续进行
        console.log(`双击了 ${e.target}`);
    }
});

以下是一个演示:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.getElementById('doubleclick').addEventListener('click', (e) => {
    if (new Date().getTime() - (e.target._lastTouch || 0) > 500) {
        //不是双击
        e.target._lastTouch = new Date().getTime();
        e.target.classList.remove("click");
        e.preventDefault(); 
    } else {
        //是双击
        e.target.classList.add("click");
        console.log(`双击了 ${e.target}`);
    }
});

<!-- language: lang-css -->

.click {
 background-color: red;
 color: white;
}

<!-- language: lang-html -->

<button id="doubleclick">双击我</button>

<!-- end snippet -->
英文:

In general, I would advise against counting clicks to check for double-clicking, as this would also apply to really slow double-clicks or clicks that (such as your example) first clicked element A, then B, then A again.

I'd recommend checking the 'last clicked' time, and if that's greater than, say, 500 ms, do not consider this click a (second, thus) double click.

Here's an example, using 500ms as a threshold:

myDoubleClickElement.addEventListener(&#39;click&#39;, (e) =&gt; {
	if (new Date().getTime() - (e.target._lastTouch || 0) &gt; 500) {
		e.target._lastTouch = new Date().getTime();
		e.preventDefault(); //does not allow the action to proceed
	} else {
	    //allows the action to proceed
		console.log(`Double click on ${e.target}`);
	}
});

Here's a demo

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.getElementById(&#39;doubleclick&#39;).addEventListener(&#39;click&#39;, (e) =&gt; {
    if (new Date().getTime() - (e.target._lastTouch || 0) &gt; 500) {
        //not a doubleclick
        e.target._lastTouch = new Date().getTime();
        e.target.classList.remove(&quot;click&quot;);
        e.preventDefault(); 
    } else {
        //a doubleclick
        e.target.classList.add(&quot;click&quot;);
        console.log(`Double click on ${e.target}`);
    }
});

<!-- language: lang-css -->

.click {
 background-color: red;
 color: white;
}

<!-- language: lang-html -->

&lt;button id=&quot;doubleclick&quot;&gt;Double click me&lt;/button&gt;

<!-- end snippet -->

答案2

得分: 0

这应该会帮助你

event.stopPropagation();

查看链接描述

英文:

This should help you

event.stopPropagation();

enter link description here

答案3

得分: 0

这是因为当点击另一个按钮时,您从未重置点击按钮的count变量,因此第二次点击按钮时,count值将直接为2。

为了解决这个问题,我建议您使用“click”类作为按钮是否已被点击的指示器。然后,您只需要检查被点击的按钮是否存在该类,如果存在,则删除它(如果不存在则添加该类)。

要检查元素是否具有该类,您可以使用以下代码:

const isClicked = element.target.classList.contains("click")

在移除所有元素上的“click”类之前,您需要执行此检查。

英文:

This is because you never reset the count variable of a clicked button when another one is clicked, so the second time you click a button, the count value will be directly 2.

To fix this I would advise you to use the "click" class as an indicator if the button has been clicked or not. You will then only have to check if the class of the clicked button is present, and if so delete it (and add the class if not)

To check if an element has the class you can use:

const isClicked = element.target.classList.contains(&quot;click&quot;)

You would need to do this check before removing the "click" class on all the elements

huangapple
  • 本文由 发表于 2023年5月11日 17:55:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定