如果鼠标光标离开按钮容器,则javascript触发脚本



我有一个JS函数,它工作得很好,当用户在x秒后单击按钮时,如果按住鼠标按钮,表单将提交,否则,如果释放鼠标,按钮将返回到预先单击的状态。然而,我发现了一个问题,如果鼠标光标离开按钮,那么表单仍然会触发并几乎破坏所有内容。

如果鼠标离开按钮或以任何方式失去焦点,我需要同时触发mouseup功能。

非常感谢。

function conf_submit(btn) {
var btn_name = $(btn).val();
var btnID = $(btn).attr('id');
var process = false;
$(btn).mousedown(function() {
btn_timeout = setTimeout(function() {
process = true;
$(btn).val('Processing..');
$(btn).attr('class', 'button btn_longpress small btn-processing');
$('#' + btnID + '_form').submit();
}, 2000);
if(process == false){
$(this).val('Release to cancel!');
$(this).attr('class', 'button btn_longpress small cancel cancel-animate jiggle');
}
});
$(btn).mouseup(function() {
clearTimeout(btn_timeout);
if(process == false){
$(this).val( btn_name );
$(this).attr('class', 'button btn_longpress small');
}
});

}

如果从mousedownmouseup函数中提取逻辑,则可以很容易地重新调整其用途。

function conf_submit(btn) {
var btn_name = $(btn).val();
var btnID = $(btn).attr('id');
var process = false;
var start = function () {
btn_timeout = setTimeout(function () {
process = true;
$(btn).val('Processing..');
$(btn).attr('class', 'button btn_longpress small btn-processing');
$('#' + btnID + '_form').submit();
}, 2000);
if (process == false) {
$(this).val('Release to cancel!');
$(this).attr('class', 'button btn_longpress small cancel cancel-animate jiggle');
}
};
var stop = function () {
clearTimeout(btn_timeout);
if (process == false) {
$(this).val(btn_name);
$(this).attr('class', 'button btn_longpress small');
}
};
$(btn).mousedown(start);
$(btn).mouseup(stop);
$(btn).mouseleave(stop);
}

您要查找的事件是"鼠标离开";事件

每次鼠标离开按钮时,下面脚本中的事件都会触发。

document.getElementById("button").addEventListener("mouseleave", () => {
alert("triggered event")
})
<button id="button">Click Me</button>

最新更新