document.activeElement 這個變數會指向目前取得focus的element
所以,我們可以利用這個變數來判斷某一個element (如:input)是否有focus
依據有無focus,然後做不同的處理方式
Example:
if( document.activeElement == element ) { if( text == "" || text == defaultText ) { inp.removeClass("ghost"); inp.val(""); } } else { if( text == "" || text == defaultText ) { inp.addClass("ghost"); inp.val(defaultText); } else { inp.removeClass("ghost"); } }
這段code是用來做下面ghost(輸入欄位預設文字)這個效果:
Reference:
http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element-has-focus
Tags: Javascript, UI, Web