Javascript 不由单击触发的焦点
当聚焦输入但聚焦事件不是来自单击时,如何触发操作Javascript 不由单击触发的焦点,javascript,jquery,Javascript,Jquery,当聚焦输入但聚焦事件不是来自单击时,如何触发操作 $('#input').focus(function(){ if(not come from click) { alert('Holla!'); } }); 使用keyup $('#input').keyup(function(){ alert('Called only when the focus is on element through keypress'); }); 不要签入焦点功能,而是在单击时删除焦
$('#input').focus(function(){
if(not come from click)
{
alert('Holla!');
}
});
使用keyup
$('#input').keyup(function(){
alert('Called only when the focus is on element through keypress');
});
不要签入焦点功能,而是在单击时删除焦点功能
要区分来自键盘和鼠标的“焦点”事件,您可以跟踪鼠标事件
首先,要了解在单击输入或选项卡时发生的事件顺序,请查看以下JSFIDLE:
在其中,我们将记录mousedown、mouseup、click、focus和blur事件\
<input type="text" id="zero"/>
<input type="text" id="one"/>
如果我们只需单击输入,然后单击另一个控件,就会得到以下结果:
- 穆斯敦
- 焦点
- 鼠标
- 点击
- 模糊
- 焦点
- 模糊
$(function() {
var one = $('#one');
one.mousedown(function() {
console.log('mousedown');
$(this).data('mousedown', true);
});
one.mouseup(function() {
console.log('mouseup');
});
one.click(function() {
console.log('click');
});
one.focus(function() {
if ($(this).data('mousedown')) {
console.log('You clicked it!');
} else {
console.log('You tabbed it!');
}
});
one.blur(function() {
console.log('blur');
$(this).data('mousedown', false);
});
});
这是一个很好的例子:你能在这里粘贴代码吗?你的功能会将浏览器发送到一个无限的警报循环中。
keyup
的问题是它会在聚焦后触发。
$(function() {
var one = $('#one');
one.mousedown(function() {
console.log('mousedown');
});
one.mouseup(function() {
console.log('mouseup');
});
one.click(function() {
console.log('click');
});
one.focus(function() {
console.log('focus');
});
one.blur(function() {
console.log('blur');
});
});
$(function() {
var one = $('#one');
one.mousedown(function() {
console.log('mousedown');
$(this).data('mousedown', true);
});
one.mouseup(function() {
console.log('mouseup');
});
one.click(function() {
console.log('click');
});
one.focus(function() {
if ($(this).data('mousedown')) {
console.log('You clicked it!');
} else {
console.log('You tabbed it!');
}
});
one.blur(function() {
console.log('blur');
$(this).data('mousedown', false);
});
});