JQ事件和事件物件
1 事件
一 .滑鼠事件
1.ready()頁面載入事件:載入文件節點
2 click()熟悉的單擊事件
3 dbclick()雙擊事件
4 mousedown() /mouseup() 滑鼠按下和鬆開事件
5 mouseover()/mouseout() 滑鼠移入和移出事件
6 mouseenter()/mouseleave() 滑鼠移入移出事件
//mouseover()/mouseout()和mouseenter()/mouseleave()的區別
首先來了解一下事件冒泡和捕獲
事件冒泡:內部事件先觸發,然後在觸發外部事件
事件捕獲:外部事件先被觸發,然後在觸發內部元素
mouseover()/mouseout() :滑鼠移入“所選元素以及後代都會觸發”
mouseenter()/mouseleave():滑鼠移入“所選元素”才會觸發,如果滑鼠移入所選元素的後代時,不會觸發(增加阻止事件冒泡功能)
<body> <div class="div1"> <div class="div2"></div> </div> <p>mouseover事件<span id="num1"></span>次</p> <p>mouseenter事件<span id="num2"></span>次</p> <script> var count1=0; var count2=0; $('.div1').mouseover(function(){ $('#num1').text(count1+=1) //通過記錄次數來看出區別,無論移入哪個元素都會加1 }) $('.div1').mouseenter(function(){ $('#num2').html(count2+=1)//只有移入指定元素才會加1 }) </script>
7 hover滑鼠懸停事件 有兩個引數(方法),滑鼠一定到指定物件以及移出時會觸發
二 鍵盤事件
1 keydown 鍵盤按下時觸發的事件
2 keyup 鍵盤松開一瞬間觸發的事件
3 keypress 鍵盤按下鬆開整個過程觸發的事件
//keydown()和keypress區別
keydown()按下任意鍵都會觸發,但keypress()事件只在按下鍵盤中任意字元鍵(A-Z)時觸發,功能鍵不會觸發(如shift ctrl 等)
4 event.which 指示按下的哪個鍵
1<script> 2$(document).keydown(function(e){ 3alert(e.which) 4}) 5$(document).keyup(function(){ 6alert("1111") 7}) 8$(document).keypress(function(e){ 9alert(e.which) 10}) 11</script>
三 表單事件
1 focus () :獲得焦點事件
2 blur(): 失去焦點事件
3 focusin() :獲得焦點事件
4 focusout() :失去焦點事件
5 change() :元素髮生改變時,觸發事件
6 select():當選中單行文字text或者多行文字areatext時,觸發事件
7 submit() :表單提交事件
//focus()和focusin() 的區別
focusin可以在父元素上檢測子元素獲得焦點的情況 而focusout可以在父元素上檢測子元素失去焦點情況
四 其他事件
1 scroll()滾動滾動條時觸發的事件
2 resize()當調整視窗大小時觸發的事件
//小案例(當滾動到一定高度出現搜尋選單)
.bar{ width: 100%; height: 50px; background: red; position:fixed; top:0; display: none; } <div class="bar"></div> $(function(){ $(window).scroll(function(){ str=$(this).scrollTop(); if(str>1000){ $('.bar').css('display','block') } //滾動條的距離scrollTop()和scrollLeft() })
2 事件物件
JQ在事件函式中預設傳遞了引數event物件,
一 event物件屬性
1 event .type 描述事件的型別
2 event.target 觸發該事件的DOM元素
3 event.currentTarget 在事件冒泡階段中的當前DOM元素,等同於 this
4 event.pageX/event.pageY 滑鼠相對於檔案左側和頂部的位置 //會隨著滾動條變化而變化
//screenX/screenY 獲取顯示器螢幕位置的座標 //整個螢幕的高度 不會隨著滾動條變化而變化
//clientX/clientY 獲取相當於頁面視口的座標 //除去上下視窗 不會隨著滾動條變化而變化
<script src="jquery-3.1.1.min.js"></script> <title>client screen page</title> <style> body{ height: 3000px; font-family: "微軟雅黑"; margin:0px; padding:0px; } #div1{ width:300px; height: 200px; border:1px solid red; position: fixed; top:0; } </style> </head> <body> <div id="div1"></div> <script> $(document).mousemove(function(e){ $('#div1').html("pageY:"+e.pageY+"<br/>"+"clientY:"+e.clientY+"<br/>"+"screenY:"+e.screenY) }) </script> </body> </html>
5 event.which 針對鍵盤和滑鼠事件,這個屬效能確定你到底按的是哪個鍵或按鈕。
event.which將event.keyCode 和 event.charCode標準化了。推薦用event.which來監視鍵盤輸入。
在mousedown、mouseup事件中,event.which屬性返回的是對應滑鼠按鈕的對映程式碼值(相當於event.button)。以下是主要的滑鼠按鈕對映程式碼對應表
Event.which屬性值 |
對應的滑鼠按鈕 |
1 |
滑鼠左健 |
2 |
滑鼠中健(滾輪鍵) |
3 |
滑鼠右健 |
6 event.preventDefault() 阻止事件的預設行為
7 event.stopPropagation() 防止冒泡事件