OKR
共同教學
jQuery
jQuery官網-jQuery API Documentation
easing函數速查表
w3school jQuery animate()
針對jQuery官網上的API文件,將專案上可能較常使用的基本函式挑選出來學習,理解函式如何使用,若有寫的不清楚的地方歡迎提供補充。
addClass()與removeClass()CodePen範例
一、使用方式
.addClass(className)
為某個元素增加指定的樣式名稱
Type: String (字串)
Type: Array (陣列)
.addClass(function(index, currentClass))
傳遞一個用來設置樣式類名的函數,返回一個或更多用空格隔開的要增加的樣式名
Type: function() (函數)
二、範例寫法
$('p').addClass('className');
$('p').addClass('className1 className2');
$('p').addClass(['className1','className2']);
$('p').removeClass('className1').addClass('className2');
//這範例是說可以為每個<li>增加class
//index代表回傳數字,從0開始
$('ul li').addClass(function(index) {
return "item-"+index; //回傳item-0,item-1,item-2...
});
//這範例是說要在當前有class="red"裡,在增加一個class="green"
$('div').addClass(function(index,currentClass)){
var classAdd; //宣告一個要增加的class
if(currentClass==="red"){
addClass="green";
$('p').text("change text");//然後p裡面的文字則會變更
}
return classAdd;
}
addClass()與removeClass()CodePen範例
一、使用方式
.removeClass(className)
為某個元素增加指定的樣式名稱
Type: String(字串)
Type: Array(陣列)
.removeClass(function(index, currentClass))
傳遞一個用來設置樣式類名的函數,返回一個或更多用空格隔開的要增加的樣式名
Type: function()
二、範例寫法
$('p').removeClass('className');
$('p').removeClass('className1 className2');
$('p').removeClass('className1').addClass('className2');
toggleClass()=addClass()與removeClass
以下範例為當點選p標籤時,會切換class="hightlight"增加/移除
<p class="blue">Click to toggle</p>
$('p').click(function(){
//當下點選的p區塊會增加class="hightlight"
$(this).toggleClass('hightlight');
})
<div id="mydiv" class="foo bar"></div>
//會去看id="mydiv"裡面是否有class="foo"
$('#mydiv').hasClass('foo');
//假如有class="foo",console會回傳true,若沒有回傳false
var mydiv = $('#mydiv').hasClass('foo');
console.log(mydiv);
attr()/remoceAttr()/prop()CodePen範例
一、使用方式
.attr(attributeName)
$('em').attr('title');
.attr(attributeName, value)
$('em').attr('title','hello,my friend');
二、範例寫法
<em title="hello,my friend">large</em>
<div></div>
var title = $('em').attr('title');
$('div').text(title);
//印出結果
hello,my friend
<em title="hello,my friend">large</em>
<div></div>
$('em').attr('title','Goodybye,my friend');
//印出結果
<em title="Goodybye,my friend">large</em>
<img src="https://picsum.photos/200/300">
$('img').attr({
width:"300",
height:"180"
});
//印出結果
<img src="https://picsum.photos/200/300" width="300" height="180">
//印出結果
<div class="demo4">
<img title="img1.gif">
<img title="img2.gif">
<img title="img3.gif">
</div>
$('.demo4 img').attr('src',function(){
return "/images/" + this.title;
//新增src屬性,並給予圖片路徑的名稱抓取為title內容
})
//印出結果
<div class="demo4">
<img title="img1.gif" src="/images/img1.gif">
<img title="img2.gif" src="/images/img2.gif">
<img title="img3.gif" src="/images/img3.gif">
</div>
//取值的時候,假如input本身有設定html屬性checked,就要使用.attr()取得字串checked
<input class="check1" type="checkbox" checked>
//若沒有設定,則會取到undefined
<input class="check2" type="checkbox">
//使用.prop()取該屬性checked值,則會取得布林值(boolean)
<input class="check3" type="checkbox" checked="true">
<input class="check4" type="checkbox" checked="false">
$('.check-1').attr('checked') //checked
$('.check-2').attr('checked') //undefined
$('.check-3').prop('checked') //true
$('.check-4').prop('checked') //false
可與attr()搭配應用
attr()/remoceAttr()/prop()CodePen範例
.removeAttr(attributeName)
$('em').removeAttr('title');
.removeAttr(attributeName, value)
$('em').removeAttr('title','hello,my friend');
.prop(propertyName)
$('input').prop('disabled',false);
$('input').prop('checked',true);
$('input').removeProp('checked');
<input type="text" value="some text">
<p></p>
var inputVal = $('input').val();
console.log(inputVal);
$('p').text("取出值為:" + inputVal);
//列印結果
取出值為:some text
以下為修改box1的css顏色
<div id="box1">1</div>
$('.box1').css("color","red");
height()/innerHeight()/outerHeight() Codepen範例
獲取元素的當前計算高度
計算視窗高度,不包含margin.padding.border
.height()
$(window).height(); //視窗高度
$(document).height(); //整個網頁的高度
height()/innerHeight()/outerHeight() Codepen範例
獲取元素的當前計算高度
計算視窗高度,包含padding,但不包含border.margin
height()/innerHeight()/outerHeight() Codepen範例
獲取元素的當前計算高度
計算視窗高度,包含padding.margin.border
width()/innerWidth()/outerWidth() Codepen範例
獲取元素的當前計算寬度
計算視窗高度,不包含margin.padding.border
.width()
$(window).width(); //視窗寬度
$(document).width(); //整個網頁的寬度
width()/innerWidth()/outerWidth() Codepen範例
獲取元素的當前計算寬度
計算視窗寬度,包含padding,但不包含border.margin
width()/innerWidth()/outerWidth() Codepen範例
在介紹offset()與position()之前先稍了解以下兩者的差別,
主要是差在「相對位置」的不同,參閱兩者範例就可以了解!
offset() - 只會以整個document、body或是說整著網站作為相對位置來抓取元素座標
Position() - 會以指定元素的層級開始往上尋找、找到第一個position為relative元素作為此元素的相對位置來抓取元素座標
獲取元素的當前計算寬度
計算視窗寬度,包含padding.margin.border
<p>我要偵測p坐標</p>
$('p').offset();
$('p').offset().left;
$('p').offset().top;
以範例結果為
left: 8,
top: 125.875
//left+計算區塊的寬度加總(outerWidth)=right坐標寬度
//計算結果 8+400=408
$(".offsetBlock").offset().left +$(".offsetBlock").outerWidth();
//top+計算區塊的寬度加總(outerHeight)=bottom坐標寬度
//計算結果 125.875+66=191.875
$(".offsetBlock").offset().top + $(".offsetBlock").outerHeight();
以範例結果為
right: 408,
bottom: 191.875
返回包含屬性top/left
<p>我要偵測p坐標</p>
$('p').position();
$('p').position().left;
$('p').position().top;
以範例結果為
left: 8,
top: 147.875
//left+計算區塊的寬度加總(outerWidth)=right坐標寬度
//計算結果 8+400=408
$(".positionBlock").position().left +$(".positionBlock").outerWidth();
//top+計算區塊的寬度加總(outerHeight)=bottom坐標寬度
//計算結果 125.875+66=191.875
$(".positionBlock").position().top + $(".positionBlock").outerHeight();
以範例結果為
right: 418,
bottom: 547.875
scrollLeft()與scrollTop() CodePen範例
var scrollLeft = $(".demo").scrollLeft();
console.log(scrollLeft);
$(".demo").scrollLeft(10);
scrollLeft()與scrollTop() CodePen範例
var scrollTop = $(".demo").scrollTop();
console.log(scrollTop);
$(".demo").scrollTop(10);
.hide([duration] [, complete])
類似.css("display","none")效果
$('.box').hide();
$('.box').hide("slow");
$('.box').hide(1000);
.show([duration] [, complete])
類似.css("display","block")效果
$('.box').show();
$('.box').show("slow");
$('.box').show(1000);
.toggle([duration] [,complete])
$('.box').toggle();
$('.box').toggle("slow");
$('.box').toggle(1000);
.animate(properties [,duration] [,easing] [,complete])
animate()寫法
$(selector).animate({styles},duration,easing,callback)
//{styles}:放樣式
//duration:動畫持續速度,values可以填數值(ex.100,1000,5000),以毫秒為單位,1000代表1秒、"slow"、"fast"
//easing:動畫效果,ex.swing(預設效果)/linear
$('.box').animate({
minHeight:'200',
width:'300'
},1500,"linear")
fadeIn()/fadeOut()/fadeTo()/fadeToggle() Codepen範例
.fadeIn( [duration ] [, complete ] )
duration是指動畫持續時間,values可以填數值(ex.100,1000,5000)、"slow"、"fast"
$('.box1').fadeIn('slow');
$('.box1').fadeIn(800);
fadeIn()/fadeOut()/fadeTo()/fadeToggle() Codepen範例
.fadeOut([duration ] [,complete])
$('.box1').fadeOut('slow');
$('.box1').fadeOut(800);
fadeIn()/fadeOut()/fadeTo()/fadeToggle() Codepen範例
.fadeTo(duration, opacity [,complete])
$(".box2").fadeTo("fast", Math.random());
$('.box2').fadeTo('slow',0.33);
$('.box2').fadeTo(250,0.25);
設定淡入淡出來切換顯示/隠藏效果
fadeIn()/fadeOut()/fadeTo()/fadeToggle() Codepen範例
.fadeToggle([duration] [,easing] [,complete])
$('.box1').fadeToggle('slow');
$('.box1').fadeToggle(800);
slideDown()/slideUp()/slideToggle() Codepen範例
.slideDown([duration] [, complete])
duration是指動畫持續時間,values可以填數值(ex.100,1000,5000)、"slow"、"fast"
$('.box1').slideDown('slow');
$('.box1').slideDown(800);
slideDown()/slideUp()/slideToggle() Codepen範例
.slideUp([duration] [, complete])
duration是指動畫持續時間,values可以填數值(ex.100,1000,5000)、"slow"、"fast"
$('.box1').slideUp('slow');
$('.box1').slideUp(800);
slideDown()/slideUp()/slideToggle() Codepen範例
.slideToggle([duration] [, complete])
duration是指動畫持續時間,values可以填數值(ex.100,1000,5000)、"slow"、"fast"
$('.box1').slideToggle('slow');
$('.box1').slideToggle(800);
設置時間以延遲隊列中後續項目的執行。
.delay(duration [,queueName])
$('#foo').slideUp(300).delay(800).fadeIn(400);
停止當前正在運行的動畫,並刪除排隊的動畫,結束動畫,一切重來
$('.box').finish();
停止當前正在運行的動畫,並結束動畫,但不會刪除排隊的動畫
$('.box').stop();
$('.box').stop().slideToggle(1000);
blur()與focus()可以搭配應用,通常用在input焦點判斷上,實際可查看codepen範例
<input id="target" type="text" value="請輸入文字">
$("#target").on("focus", function () {
//點選input文字消失事件
console.log('進到焦點')
});
$("#target").on("blur", function () {
//離開input時文字顯示事件
console.log('離開焦點')
});
- 此事件僅限於用在<input>/<textarea>/<select>元素
- 當input.textarea有輸入文字變更或是select選取狀態時
<input id="target" type="text" value="請輸入文字">
$('.input-target').on("change",function(){
console.log('文字輪入有變更')
})
$('input[type='text']').change(function() {
//也可以直接使用input[type='text']相關html屬性
});
Dom完全加載時執行,一般常見寫法如下
$(document).ready(function(){
//html頁面加載後執行
})
但依據jQuery文件手冊提到從jQuery3.0開始,僅建議使用以下語法,其他語法雖仍然有效,但已棄用
$(function () {
//html頁面加載後執行
});
resize()偵測尺寸
可以綁定當偵測瀏覽器寬度或高度時之事件
可以綁定當偵測瀏覽器滾動時之事件
//html
<p><b>Test</b> Paragraph.</p>
<p></p>
//找到第一個<p>的內文,也包含<b>裡面,結果為Test Paragraph.
var firstText = $('p').first().text();
//找到後,放入最後一個<p>裡面
$('p').last().text(firstText);
//html
<p>Test Paragraph.</p>
$('p').text('<b>Some</b> new text.');//更換<p>裡面文字
//印出結果
'<b>Some</b> new text.' >>>>注意這是一段文字,是字符串而非為HTML
//html
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
$('.demo-container').html()
//印出結果
<div class="demo-box">Demonstration Box</div>
//html
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
$('.demo-container').html('<p>All new content. <em>You bet!</em></p>');
//印出結果
<div class="demo-container">
<p>All new content. <em>You bet!</em></p>
</div>
一、使用方式
.append(content[,content])
.append(function)
二、範例寫法
//html
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('.inner').append('<p>Test</p>');
//印出結果是讓你知道增加到那裡,實際結果可參考codepen
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
//html
<div class="container">
<div class="inner">Hello:</div>
</div>
$('.inner').append(document.createTextNode('我是小明'));
//印出結果
Hello:我是小明
//html
<h2>Greetings</h2> //原本在這裡
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('.inner').append($('h2'));
//印出結果
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
<h2>Greetings</h2> //跑到這裡
</div>
append()與appendTo()方法最後執行的結果都是一樣
主要差別是在語意表達與程式撰寫時是顛倒過來的
例如:A.append(B)意思是將B放到A裡面的最後一個位置;A.appendTo(B)意思是將A放到B中的最後一個位置
//html
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('<p>Test</p>').appendTo('.inner'); //在這邊就可以看到與append()的差別
//印出結果是讓你知道增加到那裡,實際結果可參考codepen
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
//html
<h2>Greetings</h2> //原本在這裡
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('h2').appendTo($('.container')); ////在這邊就可以看到與append()的差別
//印出結果
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
<h2>Greetings</h2> //跑到這裡
</div>
剛好與append()相反
prepend()CodePen範例
一、使用方式
.prepend(content[,content])
.prepend(function)
二、範例寫法
//html
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('.inner').prepend('<p>Test</p>');
//印出結果是讓你知道增加到那裡,實際結果可參考codepen
<div class="container">
<div class="inner">
<p>Test</p>
Hello
</div>
<div class="inner">
<p>Test</p>
Goodbye
</div>
</div>
//html
<div class="container">
<div class="inner">大家好</div>
</div>
$('.inner').prepend(document.createTextNode('我是小明,'));
//印出結果
我是小明,大家好
//html
<h2>Greetings</h2> //原本在這裡
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('.inner').prepend($('h2'));
//印出結果
<div class="container">
<h2>Greetings</h2> //跑到這裡
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
prepend()與prependTo()方法最後執行的結果都是一樣
主要差別是在語意表達與程式撰寫時是顛倒過來的
例如:A.prepend(B)意思是將B放到A裡面的最前一個位置;A.prependTo(B)意思是將A放到B中的最前一個位置
//html
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('<p>Test</p>').prependTo('.inner'); //在這邊就可以看到與prepend()的差別
//印出結果是讓你知道增加到那裡,實際結果可參考codepen
<div class="container">
<div class="inner">
<p>Test</p>
Hello
</div>
<div class="inner">
<p>Test</p>
Goodbye
</div>
</div>
//html
<h2>Greetings</h2> //原本在這裡
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$('h2').prependTo($('.container')); //在這邊就可以看到與prepend()的差別
//印出結果
<div class="container">
<h2>Greetings</h2> //跑到這裡
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
一、使用方式
.even()
jQuery3.5支援,不能傳任何參數
二、範例寫法
找到該集合中的偶數,偶數計算從0開始編號
//這個範例假如<li>有六個,就會將偶數列增加背景顏色
$('li').even().css('background-color','red');
一、使用方式
.odd()
jQuery3.5支援,不能傳任何參數
二、範例寫法
找到該集合中的奇數,奇數計算從1開始編號
//這個範例假如<li>有六個,就會將奇數列增加背景顏色
$('li').odd().css('background-color','red');
一、使用方式
eq(index)
將匹配元素指定index的位置(由0開始),如果是負數,則從集合中的最後一個元素開始倒回去計數。
<ul>
<li>list item 1</li> //基準0
<li>list item 2</li>
<li>list item 3</li> //eq(2)
<li>list item 4</li> //eq(-2)
<li>list item 5</li>
</ul>
//eq(2)==>結果為將item3背景設為紅色
$('li').eq(2).css('background-color', 'red');
//eq(-2)==>結果為將item4背景設為紅色
//說明:假如item1基準為0,往負值順序為-1,-2,從最後一個元素位置開始計算,也就是item5為eq(-1),item4就為eq(-2)
$('li').eq(2).css('background-color', 'red');
一、使用方式
siblings(selector)
代表搜尋匹配元素的同胞元素
//html結構
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
//請找到class為"third-item",相鄰的li都會背景變成紅色
$('li.third-item').siblings().css('background-color', 'red');
再看一個例子
//html結構
<div><span>Hello</span></div>
<p class="selected">Hello Again</p>
<p>And Again</p>
//這個例子是請找到P元素,然後相鄰兄弟是.selected的class,然後背景變成黃色
$("p").siblings(".selected").css("background", "yellow");