<script>
$(function () {
mouseover mouseout mouseenter mouseleave的區別
$('div').mouseover(function () {
$(this).css('background', 'red');
}).mouseout(function () {
$(this).css('background', 'green');
});
$('div').mouseenter(function () {
$(this).css('background', 'red');
}).mouseleave(function () {
$(this).css('background', 'green');
});
上面的mouseover mouseout mouseenter mouseleave看不出有什么區別,mouseover mouseout在有子節點的時候會產生問題
---------------------------------------------------------------------
mouseenter()和mouseleave()這組穿過子元素不會觸發,而mouseover()和mouseout()則會觸發
$('div').mouseover(function () { //over會觸發子節點,造成多次無效的觸發
$('strong').html(function (index, value) {
return value + '1';
});
});
$('div').mouseenter(function () { //enter不會觸發子節點
$('strong').html(function (index, value) {
return value + '1';
});
});
---------------------------------------------------------------------
.keydown() 、.keyup()返回的是鍵碼,而.keypress()返回的是字符編碼。
$('input').keydown(function (e) {
alert(e.keyCode); //按下a返回65
});
$('input').keyup(function (e) {
alert(e.keyCode); //按下a返回65
});
$('input').keypress(function (e) {
alert(e.charCode); //按下a返回97
});
---------------------------------------------------------------------
focus、blur、focusin、focusout的區別
.focus()和blur()分別表示光標激活和丟失,事件觸發時機是當前元素。而focusin()和focusout()也表示光標激活和丟失,但事件觸發時機可以是子元素
$('input').focus(function () {
console.log('光標激活');
});
$('input').focusout(function () {
console.log('光標激活');
});
$('div').focus(function () { //focus和blur必須是當前元素才能激活
console.log('光標激活');
});
$('div').focusin(function () { //focusin和focusout可以讓子元素激活 div里面放一個input,結果input激活了
console.log('光標激活');
});
$('div').focusout(function () {
console.log('光標丟失');
});
---------------------------------------------------------------------
復合事件
$('div').hover(function () {
$(this).css('background', 'red');
}, function () {
$(this).css('background', 'green');
});
注意:.hover()方法是結合了mouseenter()方法和mouseleave()方法,并非mouseover()和mouseout()方法。
---------------------------------------------------------------------
toggle()方法1.9版本刪除掉了。但你又非常想用這個方法,并且不想自己編寫類似的功能,可以下載jquery - migrate.js文件,來向下兼容已被刪除掉的方法。
我們可以自己寫這樣一個方法
var flag = 1;
$('div').click(function () {
if (flag == 1) {
$(this).css('background', 'red');
flag = 2;
} else if (flag == 2) {
$(this).css('background', 'blue');
flag = 3;
} else if (flag == 3) {
$(this).css('background', 'green');
flag = 1;
}
});
})
</script>