1. 程式人生 > 實用技巧 >事件基礎及操作元素

事件基礎及操作元素

1.事件基礎

1.1. 事件概述

JavaScript 使我們有能力建立動態頁面,而事件是可以被 JavaScript 偵測到的行為。

簡單理解: 觸發--- 響應機制

網頁中的每個元素都可以產生某些可以觸發 JavaScript 的事件,例如,我們可以在使用者點選某按鈕時產生一個 事件,然後去執行某些操作。

1.2. 事件三要素

  • 事件源(誰):觸發事件的元素

  • 事件型別(什麼事件): 例如 click 點選事件

  • 事件處理程式(做啥):事件觸發後要執行的程式碼(函式形式),事件處理函式

案例程式碼

<body>
<button id="btn">唐伯虎</button>
<script>
// 點選一個按鈕,彈出對話方塊
// 1. 事件是有三部分組成 事件源 事件型別 事件處理程式 我們也稱為事件三要素
//(1) 事件源 事件被觸發的物件 誰 按鈕
var btn = document.getElementById('btn');
//(2) 事件型別 如何觸發 什麼事件 比如滑鼠點選(onclick) 還是滑鼠經過 還是鍵盤按下
//(3) 事件處理程式 通過一個函式賦值的方式 完成
btn.onclick = function() {
alert('點秋香');
}
</script>
</body>

1.3. 執行事件的步驟

  1. 獲取事件源

  2. 註冊事件 (繫結事件)

  3. 新增事件處理程式 (採取函式賦值形式)

案例程式碼

<body>
<div>123</div>
<script>
// 執行事件步驟
// 點選div 控制檯輸出 我被選中了
// 1. 獲取事件源
var div = document.querySelector('div');
// 2.繫結事件 註冊事件
// div.onclick
// 3.新增事件處理程式
div.onclick = function() {
console.log('我被選中了');
}
</script>
</body>

1.4. 常見的滑鼠事件

2. 操作元素

JavaScript的 DOM 操作可以改變網頁內容、結構和樣式,我們可以利用 DOM 操作元素來改變元素裡面的內容、屬性等。(注意:這些操作都是通過元素物件的屬性實現的)

2.1. 改變元素內容(獲取或設定)

innerText改變元素內容

<body>
<button>顯示當前系統時間</button>
<div>某個時間</div>
<p>1123</p>
<script>
// 當我們點選了按鈕, div裡面的文字會發生變化
// 1. 獲取元素
var btn = document.querySelector('button');
var div = document.querySelector('div');
// 2.註冊事件
btn.onclick = function() {
// div.innerText = '2019-6-6';
div.innerHTML = getDate();
}
function getDate() {
var date = new Date();
// 我們寫一個 2019年 5月 1日 星期三
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var day = date.getDay();
return '今天是:' + year + '年' + month + '月' + dates + '日 ' + arr[day];
}
//元素可以不用新增事件
var p = document.querySelector('p');
p.innerText = getDate();
</script>
</body>

innerText和innerHTML的區別

  • 獲取內容時的區別:

innerText會去除空格和換行,而innerHTML會保留空格和換行

  • 設定內容時的區別:

innerText不會識別html,而innerHTML會識別

案例程式碼

<body>
<div></div>
<p>
我是文字
<span>123</span>
</p>
<script>
// innerText 和 innerHTML的區別
// 1. innerText 不識別html標籤 非標準 去除空格和換行
var div = document.querySelector('div');
// div.innerText = '<strong>今天是:</strong> 2019';
// 2. innerHTML 識別html標籤 W3C標準 保留空格和換行的
div.innerHTML = '<strong>今天是:</strong> 2019';
// 這兩個屬性是可讀寫的 可以獲取元素裡面的內容
var p = document.querySelector('p');
console.log(p.innerText);
console.log(p.innerHTML);
</script>
</body>

2.2. 常用元素的屬性操作

獲取屬性的值

元素物件.屬性名

設定屬性的值

元素物件.屬性名 = 值

案例程式碼

<body>
<button id="ldh">劉德華</button>
<button id="zxy">張學友</button> <br>
<img src="images/ldh.jpg" alt="" title="劉德華">
<script>
// 修改元素屬性 src
// 1. 獲取元素
var ldh = document.getElementById('ldh');
var zxy = document.getElementById('zxy');
var img = document.querySelector('img');
// 2. 註冊事件 處理程式
zxy.onclick = function() {
img.src = 'images/zxy.jpg';
img.title = '張學友思密達';
}
ldh.onclick = function() {
img.src = 'images/ldh.jpg';
img.title = '劉德華';
}
</script>
</body>

2.3. 案例:分時問候

        // 得到當前小時數
var date = new Date();
var hours = date.getHours();
// 1.獲取元素
var div = document.querySelector('div');
var img = document.querySelector('img');
// 2.判斷小時數修改圖片和當前文字資訊
if (hours > 6.5 && hours < 8) {
div.innerHTML = '早上好!';
img.src = 'images/z.gif'
} else if (hours < 11.5) {
div.innerHTML = '上午好!';
img.src = 'images/s.gif';
} else if (hours < 14) {
div.innerHTML = '中午好!';
img.src = 'images/z.gif';
} else if (hours < 18) {
div.innerHTML = '下午好!';
img.src = 'images/x.gif';
} else {
div.innerHTML = '晚上好!';
img.src = 'images/w.gif';
}

2.4. 表單元素的屬性操作

獲取屬性的值

元素物件.屬性名

設定屬性的值

元素物件.屬性名 = 值

表單元素中有一些屬性如:disabled、checked、selected,元素物件的這些屬性的值是布林型。

案例程式碼

<body>
<button>按鈕</button>
<input type="text" value="輸入內容">
<script>
// 1. 獲取元素
var btn = document.querySelector('button');
var input = document.querySelector('input');
// 2. 註冊事件 處理程式
btn.onclick = function() {
// 表單裡面的值 文字內容是通過 value 來修改的
input.value = '被點選了';
// 如果想要某個表單被禁用 不能再點選 disabled 我們想要這個按鈕 button禁用
// btn.disabled = true;
this.disabled = true;
// this 指向的是事件函式的呼叫者 btn
}
</script>
</body>

2.5. 案例:仿京東顯示密碼

案例分析:

①核心思路:點選眼睛按鈕, 把密碼框型別改為文字框就可以看見裡面的密碼

②一個按鈕兩個狀態,點選一次,切換為文字框,繼續點選一 次切換為密碼框

③演算法:利用一個flag變數賦值為0,來判斷flag的值, 如果是0就切換為文字框,flag 設定(賦值)為1,如

果是1就切換為密碼框,flag設定為0

實現程式碼:

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: relative;
width: 400px;
margin: 200px auto;
border-bottom: 1px solid #ccc;
}

input {
width: 370px;
height: 30px;
border: 0;
outline: none;
}

.box img {
width: 24px;
position: absolute;
right: 2px;
top: 2px;
}
</style>
</head>

<body>
<div class="box">
<label for="pwd">
<img src="images/close.png" alt="" id="eye">
</label>
<input type="password" id="pwd">
</div>

<script>
// 1.獲取元素
var eye = document.getElementById('eye');
var pwd = document.getElementById('pwd');
// 2.註冊事件 處理程式
var flag = 0;
img.onclick = function () {
if (flag == 0) {
img.src = 'images/open.png';
input.type = 'text';
flag = 1;
} else {
img.src = 'images/close.png';
input.type = 'password';
flag = 0;
}
}
</script>
</body>

2.6. 樣式屬性操作

我們可以通過 JS 修改元素的大小、顏色、位置等樣式。

常用方式

方式1:通過操作style屬性

元素物件的style屬性也是一個物件!

元素物件.style.樣式屬性 = 值;

行內樣式權重較高

案例程式碼

<body>
<div></div>
<script>
// 1. 獲取元素
var div = document.querySelector('div');
// 2. 註冊事件 處理程式
div.onclick = function() {
// div.style裡面的屬性 採取駝峰命名法
this.style.backgroundColor = 'purple';
this.style.width = '250px';
}
</script>
</body>

案例:淘寶點選關閉二維碼

案例程式碼:

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: relative;
margin: 200px auto;
width: 100px;
height: 110px;
border: 1px solid #eee;
color: #ff5304;
font-size: 16px;
font-weight: 700;
text-align: center;
}

.box img {
width: 80px;
margin-top: 2px;
}

.box i {
position: absolute;
left: -23px;
top: -1px;
width: 20px;
height: 20px;
color: #eee;
line-height: 20px;
border: 1px solid #eee;
font-family: Arial, Helvetica, sans-serif;
cursor: pointer;
}
</style>
</head>

<body>
<div class="box">
手機淘寶
<img src="images/tao.png" alt="">
<i class="btn">x</i>
</div>
<script>
// 1.獲取元素
var btn = document.querySelector('.btn');
var box = document.querySelector('.box');
// 2.註冊事件 處理程式
btn.onclick = function () {
//點選按鈕就隱藏二維碼盒子
box.style.display = 'none';
}
</script>
</body>

案例:迴圈精靈圖背景

  <script>
// 1. 獲取元素 所有的小li
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
// 讓索引號 乘以 44 就是每個li 的背景y座標 index就是我們的y座標
var index = i * 44;
lis[i].style.backgroundPosition = '0 -' + index + 'px';
}
</script>

案例:顯示隱藏文字框內容

<body>
<input type="text" value="手機">
<script>
// 1.獲取元素
var text = document.querySelector('input');
// 2.註冊事件 獲得焦點事件 onfocus
text.onfocus = function() {
// console.log('得到了焦點');
if (this.value === '手機') {
this.value = '';
}
// 獲得焦點需要把文字框裡面的文字顏色變黑
this.style.color = '#333';
}
// 3. 註冊事件 失去焦點事件 onblur
text.onblur = function() {
// console.log('失去了焦點');
if (this.value === '') {
this.value = '手機';
}
// 失去焦點需要把文字框裡面的文字顏色變淺色
this.style.color = '#999';
}
</script>

</body>

方式2:通過操作className屬性

元素物件.className = 值;

因為class是關鍵字,所有使用className。

案例程式碼

<body>
<div class="first">文字</div>
<script>
// 1. 使用 element.style 獲得修改元素樣式 如果樣式比較少 或者 功能簡單的情況下使用
var test = document.querySelector('div');
test.onclick = function() {
// this.style.backgroundColor = 'purple';
// this.style.color = '#fff';
// this.style.fontSize = '25px';
// this.style.marginTop = '100px';

// 2. 我們可以通過 修改元素的className更改元素的樣式 適合於樣式較多或者功能複雜的情況
// 3. 如果想要保留原先的類名,我們可以這麼做 多類名選擇器
// this.className = 'change';
this.className = 'first change';
}
</script>
</body>

案例:密碼框格式提示錯誤資訊

案例程式碼:

<body>
<div class="register">
<input type="password" class="ipt">
<p class="message">請輸入6~16位密碼</p>
</div>
<script>
// 首先判斷的事件是表單失去焦點 onblur
// 如果輸入正確則提示正確的資訊顏色為綠色小圖示變化
// 如果輸入不是6到16位,則提示錯誤資訊顏色為紅色 小圖示變化
// 因為裡面變化樣式較多,我們採取className修改樣式
// 1.獲取元素
var ipt = document.querySelector('.ipt');
var message = document.querySelector('.message');
//2. 註冊事件 失去焦點
ipt.onblur = function() {
// 根據表單裡面值的長度 ipt.value.length
if (this.value.length < 6 || this.value.length > 16) {
// console.log('錯誤');
message.className = 'message wrong';
message.innerHTML = '您輸入的位數不對要求6~16位';
} else {
message.className = 'message right';
message.innerHTML = '您輸入的正確';
}
}
</script>
</body>