[英]jQuery handing both focus and click on an element
我正在嘗試確定微調數據輸入Web應用程序的工作流程。 在單個網頁上顯示幾個地址表單:
1. Name___________
Street_________
Phone__________
2. Name___________
Street_________
Phone__________
[...many more...]
現在我想知道用戶是否正在使用tab鍵進入第二個“Name”字段(或該記錄中的任何位置),或者他們是否使用鼠標點擊它。 (或移位標簽反向移動。)
我在焦點和點擊上為輸入字段設置了一個處理程序:
$('input').click(function() { TabulateClick(this) });
$('input').focus(function() { TabulateFocus(this) });
在處理程序中,我確定用戶正在處理哪個地址以及我們是否“切換”了地址記錄。 (如果焦點位於第一個地址的“電話”中,並且您單擊同一地址中的“名稱”字段,那么實際上並未切換記錄,因此我不會將其列表。)
function TabulateClick(field)
{
var currentAddressRecord = FindAddress(field);
if ( lastAddressRecord != currentAddressRecord )
switchedAddressesWithClick++;
lastAddressRecord = currentAddress;
}
function TabulateFocus(field)
{
var currentAddress = FindAddress(field);
if ( lastAddressRecord != currentAddressRecord )
switchedAddressesWithTab++;
lastAddressRecord = currentAddress;
}
我的問題是,當我鼠標點擊進入該字段時, focus
事件首先會觸發一個假的switchedAddressesWithTab
並更改當前地址(這是壞的 )。 當click
處理程序運行時, lastAddressRecord
被破壞。
focus
處理程序內部是否有一種方法可以知道同一對象上存在掛起的click
事件? 或者在click
處理程序中知道它以前只是由focus
處理?
這是我認為基於mousedown發生在焦點之前的事實。 見演示 。
var lastClick = null;
$('input').mousedown(function(e) {
lastClick = e.target;
}).focus(function(e){
if (e.target == lastClick) {
console.log('click');
} else {
console.log('tab');
}
lastClick = null;
});
為了解決Josiah發現的錯誤,我將代碼更改為以下內容。 見演示 。
var lastFocusedElement = null;
var isClick = false;
$('input').mousedown(function(e) {
isClick= true;
}).focus(function(e){
// To prevent focus firing when element already had focus
if (lastFocusedElement != e.target) {
if (isClick) {
console.log('click ----');
} else {
console.log('tab -----');
}
lastFocusedElement = e.target;
isClick = false;
}
});
$(document.body).focus(function(){
lastFocusedElement = document.body;
});
一個問題是當你離開窗戶並切換回來時,你不會得到“點擊”或標簽。 您在具有焦點的輸入上獲得焦點事件,但您無法確定它是標簽還是單擊,因為它既不是。
我認為這是你最接近的,我會在你的頁面上嘗試這個,看看行為是否足夠好。
你可以在jQuery中使用.on()方法。 這是在同一元素上綁定兩個事件的另一種方法。
var hasClicked = false;
$('.myinputfield').on('mousedown : click',function(e){
if (e.type == 'mousedown') {
// execute code
hasClicked = true;
}
if(e.type == 'focus' && !hasClicked) {
//execute code
console.log(e.type)
}
hasClicked = false;
});
只需綁定焦點,然后檢查事件以查看e.which == 9 // tab
。
我最初的想法沒有用(感謝@Juan)。 使用事件組合可以讓您到達目的地。 如果用戶單擊文本框,則最后一次按鍵將不是選項卡。 所有輸入都在觀察並存儲最后一個密鑰代碼以傳遞給焦點事件。 這是小提琴
var lastKeyCode = 0;
$('input').focus(function(e) {
if(lastKeyCode == 9)
// tabbed into field
else
// clicked into field
}).keydown(function(e){
if(e.which == 9) // added timeout to clear lastkeypress
setTimeout(function(){lastKeyPress = 0}, 50);
lastKeyPress = e.which; // store last key code
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.