1、addClass() removeClass()
$('div').find('h2').filter('.h2').addClass('.mother')
給選定的元素添加/刪除class,這個方法的好用之處在于,可以用它來實現各類樣式的切換。思路:提前把樣式寫好,放在一個class下面,選擇合適的時機把它添加移除到相應的元素當中。
2、width() innerWidth() outerWidth()
console.log($('.father').width()) //元素本身寬度
console.log($('.father').innerWidth()) //包含了元素padding
console.log($('.father').outerWidth()) // 包含了padding和border
console.log($('.father').outerWidth(true)) //包含了padding border margin
3、jQuery中的插入元素的方法
- insertBefore() before()
$('.xxx').insertBefore($('.yyy'))
把.xxx的元素插入到.yyy的前面,注意這個時候返回的依然是.xxx的元素,這且.xxx這個元素的是剪切的過程,不是復制
相應的before()
$('div').before($('span'))
這個的意思就是在div的前面插入span,和insertBefore()剛好相反;兩者語義不同,insertBefore()的語義更容易理解一點。需要注意的是兩者的返回值,兩者返回的都是前面的元素。
相應的:
insertAfter() // after()
appendTo() // append()
prependTo() // prepend()
都是一樣的邏輯
4.remove()和detach()
let a = $('div').remove()
$('body').append(a)
在remove()以后依然會返回那個被刪除掉的div,可以將它賦值給一個變量以后進行恢復使用。同時,detach()和remove()的區別在于,它會保留原本的操作行為,而remove不會保留這些東西。
5、事件綁定和取消
$('div').on('click mouseenter',function(){
console.log('123')
})
$('div').on({
'click' : function(){console.log('1')},
'mouseover' : function(){console.log('2')}
})
可以同時添加多個事件,中間用空格分開。而可以像下面的那個樣子,針對不同的事件觸發不同的函數。
$('div').on({
'click':function(){
console.log('1')
$('div').off('click')
},
'mouseover':function(){
console.log('2')
}
})
同一段代碼,如果添加了off()就是取消事件,如果是off()就是取消全部事件,如果是off('click')就是單獨取消一個事件。
$('div').on('click',function(){
console.log('1')
})
$('div').off()
如果是這樣寫,那么這個事件根本就沒有被執行就會被取消。注意off()的具體位置,在不同的位置會有不一樣的結果。