

js中blur和click事件的冲突
source link: https://www.deaboway.com/js%e4%b8%adblur%e5%92%8cclick%e4%ba%8b%e4%bb%b6%e7%9a%84%e5%86%b2%e7%aa%81.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

问题:当焦点在输入框时,点击取消按钮会触发blur和click事件,导致需要点击两次取消按钮才能关闭弹窗
原因:这是因为blur事件比click事件先触发,而 javascript为单线程,同一时间只能执行处理一个事件 ,所以当blur处理程序时,导致其后续click事件并不会执行
var popover = document.getElementById('popover'); var input = document.getElementById('category-name'); var btn = document.getElementById('btn-cancel'); var error = document.getElementById('error');
解决方案1:如果click事件比blur事件先触发就没有问题了,所以可以给blur事件延迟触发
var timer; input.onblur = function() { timer = setTimeout(function() { console.warn('onblur'); error.style.display = 'block'; }, 100); } btn.onclick = function() { console.warn('onclick'); clearTimeout(timer); error.style.display = 'none'; popover.style.display = 'none'; }
解决方案2:将click事件改为mousedown事件,让其优先于blur事件执行(缺点是用户体验不好,鼠标按下便触发了事件)
input.onblur = function() { console.warn('onblur'); error.style.display = 'block'; } btn.onmousedown = function() { console.warn('onmousedown'); error.style.display = 'none'; popover.style.display = 'none'; }
解决方案3:给按钮添加一个mousedown事件,在其中执行event.preventDefault()阻止浏览器默认事件,这样点击按钮时输入框就不会失去焦点了
input.onblur = function() { console.warn('onblur'); error.style.display = 'block'; } btn.onmousedown = function(e) { console.warn('onmousedown'); e.preventDefault(); } btn.onclick = function() { console.warn('onclick'); error.style.display = 'none'; popover.style.display = 'none'; }
Recommend
-
147
[BUG] Contacts Blur Add to FavoritesShare[BUG] Contacts Blur
-
47
The UIVisualEffectView class can be used to apply visual effects to a view. In this tutorial a darkened blur effect will be applied to an image. This tutorial is made with Xcode 10 and built for iOS 12.
-
51
I updated my site recently and wanted to put a bit more focus on images. To do that, I included a space for cover images in articles. They take up a chunk of the top of the page, and I’ll probably re-think this approach a...
-
16
Blur tools for Signal moxie0 on 03 Jun 2020
-
9
Motion blur & smearsMotion blur & smears home animation originally posted at
-
7
Shadows gets itself a BitmapCache Well it was a bit of a journey (https://www.sharpnado.com/shadows-leaks/), but Shadows gets finally its BitmapCache \...
-
10
Blur: 11 Years Later175,720 views•Feb 28, 2021 Head to
-
10
How to enable background blur for FaceTime video calls in iOS 15
-
5
Blurring is a commonly used visual effect when digitally editing photos and videos. One of the most common blurs used in these fields is the Gaussian blur. You may have used this tool thousands of times without ever giving it greater thought....
-
11
移动端touch拖动事件和click事件冲突问题解决 - 甜点cc - 博客园 通过一个悬浮球交互功能的案例来阐述问题,以及解决办法。
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK