一、主頁(yè)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
* { font-size: 18px; }
h2 { font-size: 22px; }
h3 { font-size: 20px; }
ul li { list-style: circle; }
</style>
</head>
<body>
<h2>JavaScript課堂案例</h2>
<hr>
<h3>Make English as your working language!!!</h3>
<h3>瀏覽器中的JavaScript:</h3>
<ul>
<li>ECMAScript: JavaScript語(yǔ)法規(guī)范</li>
<li>BOM: 瀏覽器對(duì)象模型(Browser Object Model),把瀏覽器當(dāng)成一個(gè)對(duì)象(window),通過(guò)這個(gè)對(duì)象可以操控瀏覽器</li>
<li>DOM: 文檔對(duì)象模型(Document Object Model),把整個(gè)頁(yè)面當(dāng)成一個(gè)對(duì)象(document),通過(guò)這個(gè)對(duì)象可以操作整個(gè)頁(yè)面</li>
</ul>
<hr>
<h3>課堂案例</h3>
<ol>
<li><a href="example01.html">例子1:BOM和DOM的感性認(rèn)識(shí)</a></li>
<li><a href="example02.html">例子2:成都機(jī)動(dòng)車限行查詢</a></li>
<li><a href="example03.html">例子3:延遲跳轉(zhuǎn)到百度</a></li>
<li>
<a href="example04.html">例子4:輪播廣告</a>
<span><a href="#homework01">完整效果請(qǐng)參考作業(yè)1</a></span>
</li>
<li><a href="example05.html">例子5:事件冒泡和事件捕獲</a></li>
<li><a href="example06.html">例子6:獲取事件源和訪問(wèn)相關(guān)元素</a></li>
<li><a href="example07.html">例子7:動(dòng)態(tài)添加和刪除元素</a></li>
<li><a href="example08.html">例子8:流氓浮動(dòng)廣告</a></li>
<li><a href="example09.html">例子9:jQuery實(shí)現(xiàn)表格效果</a></li>
<li><a href="example10.html">例子10:jQuery實(shí)現(xiàn)動(dòng)態(tài)列表</a></li>
<li><a href="example11.html">例子11:Ajax加載美女圖片(原生JavaScript)</a></li>
<li><a href="example12.html">例子12:Ajax加載美女圖片(jQuery)</a></li>
</ol>
<h3>課后練習(xí)</h3>
<ol>
<li>
<a name="homework01"></a>
<a href="homework01.html">練習(xí)1:輪播廣告</a>
</li>
<li><a href="homework02.html">練習(xí)2:縮略圖效果</a></li>
<li><a href="homework03.html">練習(xí)3:閃爍的方塊</a></li>
<li><a href="homework04.html">練習(xí)4:表格效果</a></li>
<li><a href="homework05.html">練習(xí)5:購(gòu)物車效果</a></li>
<li><a href="homework06.html">練習(xí)6:可拖拽的元素</a></li>
</ol>
</body>
</html>
二、BOM和DOM的感性認(rèn)識(shí)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
h1 { font: 72px arial; }
#bar { color: red; }
.foo { color: green; }
h1 { color: blue !important; }
#timer {
width: 250px;
height: 30px;
line-height: 30px;
text-align: center;
color: yellow;
background-color: blue;
float: right;
}
</style>
</head>
<body>
<div id="timer"></div>
<h1 id="bar" class="foo">Hello, world!</h1>
<button onclick="shutdown()">關(guān)閉</button>
<button onclick="openBaidu()">打開百度</button>
<script>
function openBaidu() {
window.open('https://www.baidu.com', '',
'width=300,height=200');
}
function shutdown() {
if (window.confirm('確定要退出嗎?')) {
window.close();
}
}
var weekdays = ['日', '一', '二', '三', '四', '五', '六'];
function showTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var date = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var day = now.getDay();
var timeStr = year + '年' +
(month < 10 ? '0' : '') + month + '月' +
(date < 10 ? '0' : '') + date + '日 ' +
(hour < 10 ? '0' : '') + hour + ':' +
(minute < 10 ? '0' : '') + minute + ':' +
(second < 10 ? '0' : '') + second +
' 星期<b>' + weekdays[day] + '</b>';
var div = document.getElementById('timer');
div.innerHTML = timeStr;
}
showTime();
window.setInterval(showTime, 1000);
// 1TBS風(fēng)格 - C/Unix - Dennis M. Ritchie
// Allman風(fēng)格 - FreeBSD - Allman
// while循環(huán) / do-while循環(huán) / for循環(huán)
// while循環(huán) - 不確定循環(huán)的次數(shù)
// for循環(huán) - 循環(huán)的次數(shù)是確定的
// do-while循環(huán) - 至少執(zhí)行一次
// var flag = true;
// do {
// var yearStr = window.prompt('請(qǐng)輸入年份: ');
// var year = parseInt(yearStr);
// if (year == yearStr && year > 0) {
// if (year % 4 == 0 && year % 100 != 0
// || year % 400 == 0) {
// window.alert(year + '年是閏年');
// } else {
// window.alert(year + '年不是閏年');
// }
// flag = window.confirm('是否繼續(xù)?');
// } else {
// window.alert('請(qǐng)輸入有效的年份!');
// }
// } while (flag);
</script>
</body>
</html>
三、成都機(jī)動(dòng)車限行查詢
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>成都機(jī)動(dòng)車限行查詢</title>
<style>
#search {
width: 640px;
margin: 0 auto;
text-align: center;
margin-top: 150px;
}
#carno {
display: inline-block;
width: 460px;
height: 36px;
font: 36px/36px arial;
text-align: center;
vertical-align: middle;
border: none;
outline: none;
border-bottom: 1px dotted darkgray;
}
#search input[type=button] {
width: 80px;
height: 36px;
font: 28px/36px arial;
border: none;
color: white;
background-color: red;
vertical-align: middle;
}
#result {
width: 640px;
margin: 0 auto;
text-align: center;
font: 32px/36px arial;
}
</style>
</head>
<body>
<div id="search">
<input type="text" id="carno" placeholder="請(qǐng)輸入車牌號(hào)">
<input type="button" value="查詢" onclick="showResult()">
<input type="button" value="清除" onclick="clearResult()">
</div>
<hr>
<p id="result"></p>
<script>
var p = document.getElementById('result');
function clearResult() {
p.textContent = '';
}
function showResult() {
var input = document.getElementById('carno');
var carNo = input.value;
var regex = /^[京津滬渝遼吉黑冀魯豫晉陜甘閩粵桂川云貴蘇浙皖湘鄂贛青新寧蒙藏瓊][A-Z]\s*[0-9A-Z]{5}$/;
if (regex.test(carNo)) {
var digitStr = lastDigit(carNo);
if (digitStr) {
var digit = parseInt(digitStr);
var day = new Date().getDay();
if (digit % 5 == day || digit % 5 == day - 5) {
p.innerHTML = carNo + '今日限行<br>' + p.innerHTML;
} else {
p.innerHTML = carNo + '今日不限行<br>' + p.innerHTML;
}
} else {
p.innerHTML = carNo + '不是有效的車牌號(hào)<br>' + p.innerHTML;
}
} else {
p.innerHTML = carNo + '不是有效的車牌號(hào)<br>' + p.innerHTML;
}
input.value = '';
}
function lastDigit(str) {
for (var index = str.length - 1; index >= 0; index -= 1) {
var digitStr = str[index];
if (digitStr >= '0' && digitStr <= '9') {
return digitStr;
}
}
return null;
}
</script>
</body>
</html>
四、延遲跳轉(zhuǎn)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>延遲跳轉(zhuǎn)</title>
</head>
<body>
<h3><span id="counter">5</span>秒鐘以后自動(dòng)跳轉(zhuǎn)到百度</h3>
<script>
var countDown = 5;
var span = document.getElementById('counter');
window.setTimeout(function() {
countDown -= 1;
if (countDown == 0) {
// window對(duì)象的location屬性代表瀏覽器地址欄
window.location.;
} else {
span.textContent = countDown;
// arguments是函數(shù)中的隱含對(duì)象
// 通過(guò)arguments[0]、arguments[1]可以獲得函數(shù)的參數(shù)
// 通過(guò)arguments.callee可以獲得正在被調(diào)用的函數(shù)
window.setTimeout(arguments.callee, 1000);
}
}, 1000);
</script>
</body>
</html>
五、輪播廣告
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#adv {
width: 705px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="adv">
<img src="img/slide-1.jpg" alt="" width="705">
</div>
<script>
var index = 0;
var images = ['slide-1.jpg', 'slide-2.jpg', 'slide-3.jpg', 'slide-4.jpg']
// 通過(guò)document對(duì)象獲取頁(yè)面元素的常用方法有5個(gè):
// document.getElementById('...') ==> 通過(guò)ID獲取單個(gè)元素
// document.getElementsByTagName('...') ==> 通過(guò)標(biāo)簽名獲取元素的列表
// document.getElementsByClassName('...') ==> 通過(guò)類名獲取元素的列表
// document.querySelector('...') ==> 通過(guò)樣式表選擇器獲取單個(gè)元素
// document.querySelectorAll('...') ==> 通過(guò)樣式表選擇器獲取元素的列表
var img = document.querySelector('img');
// var img = document.getElementsByTagName('img')[0];
var timerId;
startIt();
var div = document.querySelector('#adv');
div.addEventListener('mouseover', stopIt);
div.addEventListener('mouseout', startIt);
function startIt() {
timerId = window.setInterval(function() {
index += 1;
index %= images.length;
img.src = 'img/' + images[index];
}, 2000);
}
function stopIt() {
window.clearInterval(timerId);
}
</script>
</body>
</html>
六、時(shí)間冒泡和事件捕獲
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#one {
width: 400px;
height: 400px;
background-color: indianred;
margin: 60px auto;
}
#two {
width: 300px;
height: 300px;
background-color: darkseagreen;
}
#three {
width: 200px;
height: 200px;
background-color: lightsteelblue;
}
#two, #three {
position: relative;
left: 50px;
top: 50px;
}
</style>
</head>
<body>
<div id="one">
<div id="two">
<div id="three"></div>
</div>
</div>
<script>
var one = document.querySelector('#one');
var two = document.querySelector('#two');
var three = document.querySelector('#three');
// addEventListener方法的第一個(gè)參數(shù)是事件名
// 第二個(gè)參數(shù)是事件發(fā)生時(shí)需要執(zhí)行的回調(diào)函數(shù)
// 第三個(gè)參數(shù)是一個(gè)布爾值
// 如果是true表示事件捕獲 - 從外層向內(nèi)層傳遞事件
// 如果是false表示事件冒泡 - 從內(nèi)存向外層傳遞事件
// 一般情況下事件處理的方式都是事件冒泡(默認(rèn)行為)
// 如果想阻止事件的傳播行為可以調(diào)用事件對(duì)象的stopPropagation方法
one.addEventListener('click', function() {
window.alert('I am one!');
});
two.addEventListener('click', function() {
window.alert('I am two!');
});
// 事件回調(diào)函數(shù)中的第一個(gè)參數(shù)是事件對(duì)象(封裝了和事件相關(guān)的信息)
three.addEventListener('click', function(evt) {
window.alert('I am three!');
evt.stopPropagation();
});
</script>
</body>
</html>
七、獲取事件源和訪問(wèn)相關(guān)元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#buttons>button {
border: none;
outline: none;
width: 120px;
height: 40px;
font: 22px/40px Arial;
background-color: red;
color: white;
}
</style>
</head>
<body>
<div id="buttons">
<button><input type="checkbox">蘋果</button>
<button><input type="checkbox">香蕉</button>
<button><input type="checkbox">草莓</button>
<button><input type="checkbox">藍(lán)莓</button>
<button><input type="checkbox">榴蓮</button>
<button><input type="checkbox">西瓜</button>
<button><input type="checkbox">芒果</button>
<button><input type="checkbox">檸檬</button>
</div>
<script>
var buttons = document.querySelectorAll('#buttons>button');
for (var i = 0; i < buttons.length; i += 1) {
buttons[i].firstChild.addEventListener('click', function(evt) {
var checkbox = evt.target || evt.srcElement;
if (checkbox.checked) {
checkbox.parentNode.style.backgroundColor = 'lightseagreen';
} else {
checkbox.parentNode.style.backgroundColor = 'red';
}
evt.stopPropagation();
});
buttons[i].addEventListener('click', function(evt) {
// 通過(guò)事件對(duì)象的target屬性可以獲取事件源(誰(shuí)引發(fā)了事件)
// 但是有的瀏覽器是通過(guò)srcElement屬性獲取事件源的
// 可以通過(guò)短路或運(yùn)算來(lái)解決這個(gè)兼容性問(wèn)題
var button = evt.target || evt.srcElement;
// 當(dāng)獲取到一個(gè)元素之后可以通過(guò)它的屬性來(lái)獲取它的父元素、子元素以及兄弟元素
// parentNode - 父元素
// firstChild / lastChild / children - 第一個(gè)子元素 / 最后一個(gè)子元素 / 所有子元素
// previousSibling / nextSibling - 前一個(gè)兄弟元素 / 后一個(gè)兄弟元素
var checkbox = button.firstChild;
checkbox.checked = !checkbox.checked;
if (checkbox.checked) {
button.style.backgroundColor = 'lightseagreen';
} else {
button.style.backgroundColor = 'red';
}
});
}
</script>
</body>
</html>
八、動(dòng)態(tài)添加和刪除元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#container {
margin: 20px 50px;
}
#fruits li {
list-style: none;
width: 200px;
height: 50px;
font-size: 20px;
line-height: 50px;
background-color: cadetblue;
color: white;
text-align: center;
margin: 2px 0;
}
#fruits>li>a {
float: right;
text-decoration: none;
color: white;
position: relative;
right: 5px;
}
#fruits~input {
border: none;
outline: none;
font-size: 18px;
}
#fruits~input[type=text] {
border-bottom: 1px solid darkgray;
width: 200px;
height: 50px;
text-align: center;
}
#fruits~input[type=button] {
width: 80px;
height: 30px;
background-color: coral;
color: white;
vertical-align: bottom;
cursor: pointer;
}
</style>
</head>
<body>
<!-- <a href="mailto:957658@qq.com">聯(lián)系站長(zhǎng)</a> -->
<div id="container">
<ul id="fruits">
<!-- a標(biāo)簽有默認(rèn)的跳轉(zhuǎn)頁(yè)面的行為有兩種方法可以阻止它的默認(rèn)行為-->
<li>蘋果<a href="">×</a></li>
<li>香蕉<a href="">×</a></li>
<li>火龍果<a href="">×</a></li>
<li>西瓜<a href="">×</a></li>
</ul>
<input type="text" name="fruit">
<input id="ok" type="button" value="確定">
</div>
<script src="js/mylib.js"></script>
<script>
function removeItem(evt) {
evt.preventDefault();
var a = evt.target || evt.srcElement;
var li = a.parentNode;
li.parentNode.removeChild(li);
}
function addItem() {
var fruitName = input.value.trim();
if (fruitName.length > 0) {
var li = document.createElement('li');
li.textContent = fruitName;
li.style.backgroundColor = randomColor();
var a = document.createElement('a');
a.href = '';
a.textContent = '×';
a.addEventListener('click', removeItem);
li.appendChild(a);
ul.insertBefore(li, ul.firstChild);
}
input.value = '';
input.focus();
}
var anchors = document.querySelectorAll('#fruits a');
for (var i = 0; i < anchors.length; i += 1) {
anchors[i].addEventListener('click', removeItem);
}
var ul = document.getElementById('fruits');
var input = document.querySelector('#container input[type=text]');
input.addEventListener('keypress', function(evt) {
var key = evt.keyCode || evt.which;
if (key == 13) {
addItem();
}
});
var okButton = document.querySelector('#ok');
okButton.addEventListener('click', addItem);
</script>
</body>
</html>
九、流氓浮動(dòng)廣告
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#container {
margin: 20px 50px;
}
#fruits li {
list-style: none;
width: 200px;
height: 50px;
font-size: 20px;
line-height: 50px;
background-color: cadetblue;
color: white;
text-align: center;
margin: 2px 0;
}
#fruits>li>a {
float: right;
text-decoration: none;
color: white;
position: relative;
right: 5px;
}
#fruits~input {
border: none;
outline: none;
font-size: 18px;
}
#fruits~input[type=text] {
border-bottom: 1px solid darkgray;
width: 200px;
height: 50px;
text-align: center;
}
#fruits~input[type=button] {
width: 80px;
height: 30px;
background-color: coral;
color: white;
vertical-align: bottom;
cursor: pointer;
}
</style>
</head>
<body>
<!-- <a href="mailto:957658@qq.com">聯(lián)系站長(zhǎng)</a> -->
<div id="container">
<ul id="fruits">
<!-- a標(biāo)簽有默認(rèn)的跳轉(zhuǎn)頁(yè)面的行為有兩種方法可以阻止它的默認(rèn)行為-->
<li>蘋果<a href="">×</a></li>
<li>香蕉<a href="">×</a></li>
<li>火龍果<a href="">×</a></li>
<li>西瓜<a href="">×</a></li>
</ul>
<input type="text" name="fruit">
<input id="ok" type="button" value="確定">
</div>
<script src="js/mylib.js"></script>
<script>
function removeItem(evt) {
evt.preventDefault();
var a = evt.target || evt.srcElement;
var li = a.parentNode;
li.parentNode.removeChild(li);
}
function addItem() {
var fruitName = input.value.trim();
if (fruitName.length > 0) {
var li = document.createElement('li');
li.textContent = fruitName;
li.style.backgroundColor = randomColor();
var a = document.createElement('a');
a.href = '';
a.textContent = '×';
a.addEventListener('click', removeItem);
li.appendChild(a);
ul.insertBefore(li, ul.firstChild);
}
input.value = '';
input.focus();
}
var anchors = document.querySelectorAll('#fruits a');
for (var i = 0; i < anchors.length; i += 1) {
anchors[i].addEventListener('click', removeItem);
}
var ul = document.getElementById('fruits');
var input = document.querySelector('#container input[type=text]');
input.addEventListener('keypress', function(evt) {
var key = evt.keyCode || evt.which;
if (key == 13) {
addItem();
}
});
var okButton = document.querySelector('#ok');
okButton.addEventListener('click', addItem);
</script>
</body>
</html>
十、jQuery實(shí)現(xiàn)表格效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#data {
border-collapse: collapse;
}
#data td, #data th {
width: 120px;
height: 40px;
text-align: center;
border: 1px solid black;
}
#buttons {
margin: 10px 0;
}
</style>
</head>
<body>
<table id="data">
<caption>數(shù)據(jù)統(tǒng)計(jì)表</caption>
<tbody>
<tr>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>身高</th>
<th>體重</th>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
</tbody>
</table>
<div id="buttons">
<button id="pretty">隔行換色</button>
<button id="clear">清除數(shù)據(jù)</button>
<button id="remove">刪單元格</button>
<button id="hide">隱藏表格</button>
</div>
<!-- jQuery: Write Less Do More -->
<!-- 加載本地的jQuery文件適合開發(fā)和測(cè)試時(shí)使用 -->
<script src="js/jquery.min.js"></script>
<!-- 下面的方式適合商業(yè)項(xiàng)目通過(guò)CDN服務(wù)器來(lái)加速獲取jQuery的JS文件 -->
<!-- <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> -->
<script>
// JavaScript Object Notation == JSON
var stu = {
'id': 1001,
'name': '駱昊',
'age': 15,
'study': function(course) {
alert(this.name + '正在學(xué)習(xí)' + course);
},
'watchAv': function() {
if (this.age >= 18) {
alert(this.name + '正在觀看島國(guó)動(dòng)作片');
} else {
alert(this.name + '只能觀看《熊出沒》');
}
}
};
stu.study('Python');
stu.watchAv();
$(function() {
$('#hide').on('click', function() {
// 根據(jù)樣式表選擇器獲取元素 獲取到的不是原生的JS對(duì)象
// 而是經(jīng)過(guò)jQuery封裝過(guò)后的對(duì)象(有更多的方法方便操作)
$('#data').fadeOut(2000);
});
$('#remove').on('click', function() {
$('#data tr:gt(0):last-child').remove();
});
$('#clear').on('click', function() {
$('#data tr:gt(0)>td').empty();
});
$('#pretty').on('click', function() {
$('#data tr:gt(0):odd').css({
'background-color': '#ccc',
'font-size': '36px',
'font-weight': 'bolder'
});
$('#data tr:gt(0):even').css('background-color', '#abc');
});
});
</script>
</body>
</html>
十一、jQuery實(shí)現(xiàn)動(dòng)態(tài)列表
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#container {
margin: 20px 50px;
}
#fruits li {
list-style: none;
width: 200px;
height: 50px;
font-size: 20px;
line-height: 50px;
background-color: cadetblue;
color: white;
text-align: center;
margin: 2px 0;
}
#fruits>li>a {
float: right;
text-decoration: none;
color: white;
position: relative;
right: 5px;
}
#fruits~input {
border: none;
outline: none;
font-size: 18px;
}
#fruits~input[type=text] {
border-bottom: 1px solid darkgray;
width: 200px;
height: 50px;
text-align: center;
}
#fruits~input[type=button] {
width: 80px;
height: 30px;
background-color: coral;
color: white;
vertical-align: bottom;
cursor: pointer;
}
</style>
</head>
<body>
<div id="container">
<ul id="fruits">
<li>蘋果<a href="">×</a></li>
<li>香蕉<a href="">×</a></li>
<li>火龍果<a href="">×</a></li>
<li>西瓜<a href="">×</a></li>
</ul>
<input id='name' type="text" name="fruit">
<input id="ok" type="button" value="確定">
</div>
<script src="js/jquery.min.js"></script>
<script>
function removeItem(evt) {
evt.preventDefault();
// $函數(shù)的第四種用法:參數(shù)是原生的JS對(duì)象
// 將原生的JS對(duì)象包裝成對(duì)應(yīng)的jQuery對(duì)象
$(evt.target).parent().remove();
}
// $函數(shù)的第一種用法: 參數(shù)是另一個(gè)函數(shù)
// 傳入的函數(shù)是頁(yè)面加載完成之后要執(zhí)行的回調(diào)函數(shù)
// $(document).ready(function() {});
$(function() {
// $函數(shù)的第二種用法:參數(shù)是一個(gè)選擇器字符串
// 獲取元素并得到與之對(duì)應(yīng)的jQuery對(duì)象(偽數(shù)組)
$('#fruits a').on('click', removeItem);
$('#ok').on('click', function() {
var fruitName = $('#name').val().trim();
if (fruitName.length > 0) {
$('#fruits').append(
// $函數(shù)的第三種用法:參數(shù)是一個(gè)標(biāo)簽字符串
// 創(chuàng)建新元素并得到與之對(duì)應(yīng)的jQuery對(duì)象
$('<li>').text(fruitName).append(
$('<a>').attr('href', '').text('×').on('click', removeItem)
)
);
}
// 對(duì)jQuery對(duì)象使用下標(biāo)運(yùn)算或調(diào)用get()方法會(huì)得到原生JS對(duì)象
$('#name').val('').get(0).focus();
});
});
</script>
</body>
</html>
十二、Ajax加載美女圖片(原生JavaScript)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="ok">換一組</button>
<div id="container"></div>
<!-- HTML: Hyper-Text Markup Language -->
<!-- XML: eXtensible Markup Language -->
<!-- XML最為重要的用途是在兩個(gè)異構(gòu)的系統(tǒng)之間交換數(shù)據(jù) -->
<!-- 現(xiàn)在這項(xiàng)功能基本上被JSON和YAML格式替代了 -->
<!-- Ajax: Asynchronous JavaScript and XML -->
<!-- 通過(guò)JavaScript代碼向服務(wù)器發(fā)起異步請(qǐng)求并獲得數(shù)據(jù) -->
<!-- 異步請(qǐng)求:在不中斷用戶體驗(yàn)的前提下向服務(wù)器發(fā)出請(qǐng)求 -->
<!-- 獲得數(shù)據(jù)后可以通過(guò)DOM操作對(duì)頁(yè)面進(jìn)行局部刷新加載服務(wù)器返回的數(shù)據(jù) -->
<script>
(function() {
var div = document.getElementById('container');
var button = document.getElementById('ok');
button.addEventListener('click', function() {
// 1. 創(chuàng)建異步請(qǐng)求對(duì)象
var xhr = new XMLHttpRequest();
if (xhr) {
var url = 'http://api.tianapi.com/meinv/?key=772a81a51ae5c780251b1f98ea431b84&num=10';
// 2. 配置異步請(qǐng)求
xhr.open('get', url, true);
// 3. 綁定事件回調(diào)函數(shù)(服務(wù)器成功響應(yīng)后要干什么)
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
div.innerHTML = '';
// 5. 解析服務(wù)器返回的JSON格式的數(shù)據(jù)
var jsonObj = JSON.parse(xhr.responseText);
var array = jsonObj.newslist;
// 6. 通過(guò)DOM操作實(shí)現(xiàn)頁(yè)面的局部刷新
for (var i = 0; i < array.length; i += 1) {
var img = document.createElement('img');
img.src = array[i].picUrl;
img.width = '250';
div.appendChild(img);
}
}
};
// 4. 發(fā)出請(qǐng)求
xhr.send();
} else {
alert('使用垃圾瀏覽器還想看美女,做夢(mèng)!');
}
});
})();
</script>
</body>
</html>
十三、Ajax加載美女圖片(jQuery)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="ok">換一組</button>
<div id="container"></div>
<script src="js/jquery.min.js"></script>
<script>
$(function() {
$('#ok').on('click', function() {
var url = 'http://api.tianapi.com/meinv/?key=772a81a51ae5c780251b1f98ea431b84&num=10';
$.getJSON(url, function(jsonObj) {
$('#container').empty();
$.each(jsonObj.newslist, function(index, mm) {
$('#container').append(
$('<img>').attr('width', '250').attr('src', mm.picUrl)
);
});
});
});
});
</script>
</body>
</html>
作業(yè)一
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#adv {
width: 940px;
margin: 0 auto;
}
#adv ul {
width: 120px;
height: 30px;
margin: 0 auto;
position: relative;
top: -30px;
}
#adv li {
width: 30px;
height: 30px;
list-style: none;
float: left;
color: #ccc;
cursor: pointer;
}
#adv li:first-child {
color: lightseagreen;
}
</style>
</head>
<body>
<div id="adv">
<img src="img/slide-1.jpg" alt="">
<ul>
<li class="dot">●</li>
<li class="dot">●</li>
<li class="dot">●</li>
<li class="dot">●</li>
</ul>
</div>
<script>
var img = document.querySelector('#adv>img');
var items = document.querySelectorAll('#adv li');
var timerId = 0;
for (var i = 0; i < items.length; i += 1) {
items[i].index = i;
items[i].addEventListener('mouseover', function(evt) {
index = evt.target.index;
changeItemsColor(index);
img.src = 'img/' + images[index];
if (timerId != 0) {
window.clearInterval(timerId);
timerId = 0;
}
});
items[i].addEventListener('mouseout', startIt);
}
var images = ['slide-1.jpg', 'slide-2.jpg', 'slide-3.jpg', 'slide-4.jpg'];
var index = 0;
startIt();
function startIt() {
if (timerId == 0) {
timerId = window.setInterval(function() {
index += 1;
index %= images.length;
changeItemsColor(index);
img.src = 'img/' + images[index];
}, 2000);
}
}
function changeItemsColor(index) {
for (var i = 0; i < items.length; i += 1) {
items[i].style.color = '#ccc';
}
items[index].style.color = 'lightseagreen';
}
</script>
</body>
</html>
作業(yè)二
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
#container {
margin: 10px 20px;
}
#container li {
float: left;
list-style: none;
width: 60px;
height: 60px;
}
</style>
</head>
<body>
<div id="container">
<img src="img/picture-1.jpg" alt="狗屎">
<ul id="items">
<li><img src="img/thumb-1.jpg" alt=""></li>
<li><img src="img/thumb-2.jpg" alt=""></li>
<li><img src="img/thumb-3.jpg" alt=""></li>
</ul>
</div>
<script>
var img = document.querySelector('#container>img');
var images = document.querySelectorAll('#items img');
for (var i = 0; i < images.length; i += 1) {
// 事件回調(diào)函數(shù)在for循環(huán)的時(shí)候并沒有執(zhí)行所以也取不到循環(huán)變量i當(dāng)前的值
// JavaScript是動(dòng)態(tài)弱類型語(yǔ)言可以在運(yùn)行時(shí)動(dòng)態(tài)的添加(或刪除)對(duì)象的屬性
images[i].picture = 'img/picture-' + (i + 1) + '.jpg';
images[i].addEventListener('mouseover', function(evt) {
img.src = evt.target.picture;
});
}
</script>
</body>
</html>
作業(yè)三
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#container {
width: 800px;
height: 400px;
margin: 10px auto;
border: 1px solid black;
overflow: hidden;
}
#buttons {
width: 800px;
margin: 10px auto;
text-align: center;
}
#add, #fla {
border: none;
outline: none;
width: 80px;
height: 30px;
background-color: red;
color: white;
font-size: 16px;
cursor: pointer;
}
.small {
width: 80px;
height: 80px;
float: left;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="buttons">
<button id="add">添加</button>
<button id="fla">閃爍</button>
</div>
<script src="js/mylib.js"></script>
<script>
var bigDiv = document.querySelector('#container');
var addButton = document.querySelector('#add');
addButton.addEventListener('click', function() {
var smallDiv = document.createElement('div');
smallDiv.className = 'small';
// smallDiv.style.width = '80px';
// smallDiv.style.height = '80px';
// smallDiv.style.float = 'left';
smallDiv.style.backgroundColor = randomColor();
bigDiv.insertBefore(smallDiv, bigDiv.firstChild);
});
var flaButton = document.querySelector('#fla');
var isFlashing = false;
var timerId;
flaButton.addEventListener('click', function(evt) {
isFlashing = !isFlashing;
if (isFlashing) {
timerId = window.setInterval(function() {
var divs = document.querySelectorAll('#container>div');
for (var i = 0; i < divs.length; i += 1) {
divs[i].style.backgroundColor = randomColor();
}
}, 200);
flaButton.textContent = '暫停';
} else {
window.clearInterval(timerId);
flaButton.textContent = '閃爍';
}
});
</script>
</body>
</html>
作業(yè)四
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#data {
border-collapse: collapse;
}
#data td, #data th {
width: 120px;
height: 40px;
text-align: center;
border: 1px solid black;
}
#buttons {
margin: 10px 0;
}
</style>
</head>
<body>
<table id="data">
<caption>數(shù)據(jù)統(tǒng)計(jì)表</caption>
<tbody>
<tr>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>身高</th>
<th>體重</th>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>Item3</td>
<td>Item4</td>
<td>Item5</td>
</tr>
</tbody>
</table>
<div id="buttons">
<button id="pretty">隔行換色</button>
<button id="clear">清除數(shù)據(jù)</button>
<button id="remove">刪單元格</button>
<button id="hide">隱藏表格</button>
</div>
<script src="js/mylib.js"></script>
<script>
function prettify() {
var trs = document.querySelectorAll('#data tr');
for (var i = 1; i < trs.length; i += 1) {
trs[i].style.backgroundColor =
i % 2 == 0 ? 'lightgray' : 'lightsteelblue';
}
}
function clear() {
var tds = document.querySelectorAll('#data td');
for (var i = 0; i < tds.length; i += 1) {
tds[i].textContent = '';
}
}
function removeLastRow() {
var table = document.getElementById('data');
if (table.rows.length > 1) {
table.deleteRow(table.rows.length - 1);
}
}
function hideTable() {
var table = document.getElementById('data');
table.style.visibility = 'hidden';
}
+function() {
var prettyBtn = document.querySelector('#pretty');
prettyBtn.addEventListener('click', prettify)
var clearBtn = document.querySelector('#clear');
clearBtn.addEventListener('click', clear);
var removeBtn = document.querySelector('#remove');
removeBtn.addEventListener('click', removeLastRow);
var hideBtn = document.querySelector('#hide');
hideBtn.addEventListener('click', hideTable);
}();
</script>
</body>
</html>
作業(yè)五
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
body {
width: 960px;
margin: 20px auto;
}
#cart {
margin: 0 auto;
width: 850px;
}
#cart-header {
height: 40px;
background-color: lightgray;
margin-bottom: 20px;
}
#cart-header div {
line-height: 40px;
}
.left {
float: left;
}
.right {
float: right;
}
.w110 {
width: 100px;
}
.ml10 {
margin-left: 10px;
}
.w120 {
width: 120px;
}
.w250 {
width: 250px;
}
.center {
text-align: center;
}
.w20 {
width: 20px;
}
.w90 {
width: 90px;
}
.clear {
clear: both;
}
#cart-items>div {
height: 100px;
}
#cart-items>div>div {
line-height: 100px;
}
.w250 span {
display: inline-block;
font-size: 12px;
line-height: 16px !important;
}
.single-item {
border-bottom: 1px solid gray;
}
.small-button {
display: inline-block;
width: 20px;
height: 20px;
border: none;
}
.big-button {
color: white;
background-color: red;
display: inline-block;
width: 120px;
height: 40px;
border: none;
font-size: 22px;
}
#totalCount, #totalPrice {
color: red;
}
#totalPrice {
font: bolder 20px Arial;
display: inline-block;
width: 150px;
}
#cart a {
text-decoration: none;
}
#cart a:link, #cart a:visited, #cart a:active {
color: gray;
}
</style>
</head>
<body>
<div id="cart">
<div id="cart-header">
<div class="left w110 ml10">
<input id="selectAll" type="checkbox">
<label for="selectAll">全選</label>
</div>
<div class="left w250">商品</div>
<div class="left w120 center">單價(jià)</div>
<div class="left w120 center">數(shù)量</div>
<div class="left w120 center">小計(jì)</div>
<div class="left w120 center">操作</div>
</div>
<div id="cart-items">
<div class="clear single-item">
<div class="left w20 ml10">
<input name="selectOne" type="checkbox">
</div>
<div class="left w90">
<a href="">
<img src="img/a1.jpg">
</a>
</div>
<div class="left w250">
<span>
海瀾之家/Heilan Home春裝商務(wù)白襯衫男修身HNCAD3A067Y 漂白(69) 漂
</span>
</div>
<div class="left w120 center">¥<span class="price">138.00</span></div>
<div class="left w120 center">
<button class="small-button">-</button>
<input class="center count" type="text" size="2" value="1">
<button class="small-button">+</button>
</div>
<div class="left w120 center">¥<span>138.00</span></div>
<div class="left w120 center">
<a href="javascript:void(0);">刪除</a>
</div>
</div>
<div class="clear single-item">
<div class="left w20 ml10">
<input name="selectOne" type="checkbox">
</div>
<div class="left w90">
<a href="">
<img src="img/a2.jpg">
</a>
</div>
<div class="left w250">
<span>
HLA海瀾之家長(zhǎng)袖襯衫男牛津紡休閑干凈透氣HNEAJ1E048A淺灰
</span>
</div>
<div class="left w120 center">¥<span class="price">128.00</span></div>
<div class="left w120 center">
<button class="small-button">-</button>
<input class="center count" type="text" size="2" value="1">
<button class="small-button">+</button>
</div>
<div class="left w120 center">¥<span>128.00</span></div>
<div class="left w120 center">
<a href="javascript:void(0);">刪除</a>
</div>
</div>
<div class="clear single-item">
<div class="left w20 ml10">
<input name="selectOne" type="checkbox">
</div>
<div class="left w90">
<a href="">
<img src="img/a3.jpg">
</a>
</div>
<div class="left w250">
<span>
HLA海瀾之家牛津紡清新休閑襯衫2018春季新品質(zhì)感柔軟長(zhǎng)袖襯衫男
</span>
</div>
<div class="left w120 center">¥<span class="price">99.00</span></div>
<div class="left w120 center">
<button class="small-button">-</button>
<input class="center count" type="text" size="2" value="1">
<button class="small-button">+</button>
</div>
<div class="left w120 center">¥99.00</div>
<div class="left w120 center">
<a href="javascript:void(0);">刪除</a>
</div>
</div>
</div>
<div id="cart-footer">
<div class="clear left">
<a id="clearSelected" href="javascript:void(0);">刪除選中商品</a>
</div>
<div class="right">
<span>總共選中了<span id="totalCount">0</span>件商品</span>
<span>總計(jì): <span id="totalPrice">¥0.00</span></span>
<button id="pay" class="big-button">去結(jié)算</button>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script>
function calcTotal() {
var amountsInput = $('.single-item input[type=text]');
var pricesSpan = $('.single-item .price');
var checkboxes = $('.single-item input[type=checkbox]');
var totalAmount = 0;
var totalPrice = 0;
amountsInput.each(function(index) {
if (checkboxes[index].checked) {
var amount = parseInt($(this).val());
totalAmount += amount;
var price = parseFloat($(pricesSpan[index]).text());
var currentPrice = (price * amount).toFixed(2);
$(this).parent().next().find('span').text(currentPrice);
totalPrice += parseFloat(currentPrice);
}
});
$('#totalCount').text(totalAmount);
$('#totalPrice').text('¥' + totalPrice.toFixed(2));
}
$(function() {
$('#selectAll').on('click', function(evt) {
$('.single-item input[type=checkbox]').prop('checked', evt.target.checked);
calcTotal();
});
$('.single-item button').on('click', function(evt) {
var op = $(evt.target).text();
if (op == '-') {
var numInput = $(evt.target).next();
var num = parseInt(numInput.val());
if (num > 1) {
numInput.val(num - 1);
}
} else {
var numInput = $(evt.target).prev();
var num = parseInt(numInput.val());
if (num < 200) {
numInput.val(num + 1);
}
}
$(evt.target).parent().parent().find('input[type=checkbox]').prop('checked', true);
calcTotal();
});
$('.single-item input[type=checkbox]').on('click', function() {
calcTotal();
});
$('.single-item a').on('click', function(evt) {
if (confirm('確定要?jiǎng)h除該商品嗎?')) {
$(evt.target).parent().parent().remove();
calcTotal();
}
});
$('#clearSelected').on('click', function() {
if (confirm('確定要?jiǎng)h除選中的商品嗎?')) {
$('.single-item').each(function() {
if ($(this).find('input:checkbox').prop('checked')) {
$(this).remove();
}
});
calcTotal();
}
});
});
</script>
</body>
</html>
作業(yè)六
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#one, #two, #three {
width: 200px;
height: 200px;
position: fixed;
}
#one {
left: 50px;
top: 50px;
background-color: lightpink;
}
#two {
left: 200px;
top: 150px;
background-color: lightgreen;
}
#three {
right: 30px;
top: 100px;
background-color: lightgoldenrodyellow;
}
</style>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<script src="js/jquery.min.js"></script>
<script>
$(function() {
makeDraggable($('#one'));
makeDraggable($('#two'));
makeDraggable($('#three'));
});
var draggables = [];
function makeDraggable(jqElem) {
draggables.push(jqElem);
jqElem.on('mousedown', function(evt) {
this.isMouseDown = true;
this.oldX = evt.clientX;
this.oldY = evt.clientY;
this.oldLeft = parseInt($(evt.target).css('left'));
this.oldTop = parseInt($(evt.target).css('top'));
$.each(draggables, function(index, elem) {
elem.css('z-index', '0');
});
$(evt.target).css('z-index', '99');
})
.on('mousemove', function(evt) {
if (this.isMouseDown) {
var dx = evt.clientX - this.oldX;
var dy = evt.clientY - this.oldY;
$(evt.target).css('left', this.oldLeft + dx + 'px');
$(evt.target).css('top', this.oldTop + dy + 'px');
}
})
.on('mouseup', function(evt) {
this.isMouseDown = false;
})
.on('mouseout', function(evt) {
this.isMouseDown = false;
});
}
</script>
</body>
</html>