27

js中blur和click事件的冲突

 4 years ago
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.
neoserver,ios ssh client

问题:当焦点在输入框时,点击取消按钮会触发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';
}
 

参考: https://www.jianshu.com/p/ad8569eaca0c


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK