一、事件綁定
1、概述
事件綁定(2種):
eventName(function(){})
綁定對應事件名的監聽, 例如:$(‘#div’).click(function(){});on(eventName, funcion(){})
通用的綁定事件監聽, 例如:$(‘#div’).on(‘click’, function(){})優缺點:
eventName: 編碼方便, 但只能加一個監聽, 且有的事件監聽不支持
on: 編碼不方便, 可以添加多個監聽, 且更通用
事件解綁:
- off(eventName)
事件的座標:
- event.clientX, event.clientY 相對於視口的左上角
- event.pageX, event.pageY 相對於頁面的左上角
- event.offsetX, event.offsetY 相對於事件元素左上角
事件相關處理:
- 停止事件冒泡 : event.stopPropagation()
- 阻止事件默認行爲 : event.preventDefault()
2,使用示例
操作區域:
<body style="height: 2000px;">
<div class="out">
外部DIV
<div class="inner">內部div</div>
</div>
<div class='divBtn'>
<button id="btn1">取消綁定所有事件</button>
<button id="btn2">取消綁定mouseover事件</button>
<button id="btn3">測試事件座標</button>
<a href="http://www.baidu.com" id="test4">百度一下</a>
</div>
需求:
- 給.out綁定點擊監聽(用兩種方法綁定)
/*$('.out').click(function () {
console.log('click out')
})*/
$('.out').on('click', function () {
console.log('on click out')
})
- 給.inner綁定鼠標移入和移出的事件監聽(用3種方法綁定)
/*
$('.inner')
.mouseenter(function () { // 進入
console.log('進入')
})
.mouseleave(function () { // 離開
console.log('離開')
})
*/
/*
$('.inner')
.on('mouseenter', function () {
console.log('進入2')
})
.on('mouseleave', function () {
console.log('離開2')
})
*/
$('.inner').hover(function () {
console.log('進入3')
}, function () {
console.log('離開3')
})
- 點擊btn1解除.inner上的所有事件監聽
$('#btn1').click(function () {
$('.inner').off()
})
- 點擊btn2解除.inner上的mouseover事件
$('#btn2').click(function () {
$('.inner').off('mouseenter')
})
- 點擊btn3得到事件座標
$('#btn3').click(function (event) { // event事件對象
console.log(event.offsetX, event.offsetY) // 原點爲事件元素的左上角
console.log(event.clientX, event.clientY) // 原點爲窗口的左上角
console.log(event.pageX, event.pageY) // 原點爲頁面的左上角
})
- 點擊.inner區域, 外部點擊監聽不響應
$('.inner').click(function (event) {
console.log('click inner')
//停止事件冒泡
event.stopPropagation()
})
- 點擊鏈接, 如果當前時間是偶數不跳轉
$('#test4').click(function (event) {
if(Date.now()%2===0) {
event.preventDefault()
}
})
二、css
操作區域:
<p style="color: blue;">北京烤鴨</p>
<p style="color: green;">宮保雞丁</p>
需求:
得到第一個p標籤的顏色
console.log($(‘p:first’).css(‘color’))設置所有p標籤的文本顏色爲red
$(‘p’).css(‘color’, ‘red’)- 設置第2個p的字體顏色(#ff0011),背景(blue),寬(300px), 高(30px)
$('p:eq(1)').css({
color: '#ff0011',
background: 'blue',
width: 300,
height: 30
})