一. input標簽的accept屬性
當我們上傳文件或者注冊上傳頭像時,我們可以一般都是使用:
<input type="file" id="my_file">
但是這樣的話,所有文件都會顯示出來,這里以上傳頭像為例,一點擊選擇文件,所有跟圖片無關的文件也會顯示出來:

這時可以給input標簽增加一個accept屬性,讓它只顯示圖片相關的文件:
<input type="file" id="my_file" accept="image/*" >
現在再來看看效果:

二. JQuery綁定keyDown事件
一般登錄時,輸完之后點擊回車即可登錄,這是綁定了事件,我們可以用標簽選擇器來給所有input標簽綁定keyDown事件。
首先提一下window.event事件,event代表事件的狀態,例如觸發event對象的元素、鼠標的位置及狀態、按下的鍵等等。event對象只在事件發生的過程中才有效。 event的某些屬性只對特定的事件有意義。比如,fromElement 和 toElement 屬性只對 onmouseover 和 onmouseout 事件有意義。 event事件屬性:
altKey, button, cancelBubble, clientX, clientY, ctrlKey, fromElement, keyCode, offsetX, offsetY,
propertyName, returnValue, screenX, screenY, shiftKey, srcElement, srcFilter, toElement, type, x, y
詳情點擊--》》API文檔。
$('input').keydown(function () {
let e = window.event||arguments[0];
#回車鍵ascii碼為13
if (e.keyCode == 13){
alert('你按下回車了!!!')
});
實際上event事件還有一個event.which事件對象,針對鍵盤和鼠標事件,這個屬性能確定你到底按的是哪個鍵。官方推薦用 event.which 來監視鍵盤輸入。更多細節請參閱: event.charCode on the MDC.
用event.which時只需將e.keyCode改為e.which即可:
$('input').keydown(function () {
let e = window.event||arguments[0];
#回車鍵ascii碼為13
if (e.which == 13){
alert('你按下回車了!!!')
});
鍵盤事件:https://www.jquery123.com/keydown/
小例子,給body綁定按鍵事件,按下Backspace鍵返回上一級頁面:
$('body').keydown(function () {
let e = window.event||arguments[0];
if(e.keyCode==8){
history.back();
}
});
