JavaScript-05-內建物件window和document
阿新 • • 發佈:2018-12-31
一、window
全域性函式+動態跳轉:window.location.href
<script text="text/javascript"> //第一大作用 //1.1 所有全域性的變數都是window的屬性 //1.2 所有的全域性函式都是window的方法 //全域性的變數 varage = 17; console.log(window.age); //全域性的函式 function Dog() { var name = '張三'; console.log(name + '這是一條可愛的狗') } Dog(); window.Dog(); // window.alert('哈哈'); // window.console.log('Hello');//全域性的function Person() { console.log(this); } Person();//window Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} new Person();//Person Person {} //第二大作用 //1.動態的跳轉 alert(0);//阻斷 window.location.href= 'http://www.baidu.com'; //2.互動 window.location.href = 'HK://openCamera?user=123&pwd=000'; </script>
二、document
2.1更改圖片
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>document的常用操作</title> <script text="text/javascript"> function changeImage() { //更改圖片 //1.獲取網頁中的影象標籤 //1.1 getElementsByClassName var img = document.getElementsByClassName('icon')[0]; console.log(img); //2.改變src 屬性 img.src = './image/icon_02.png'; } </script> </head> <body> <img class="icon" src="./image/icon_01.png" alt=""> <p></p> <button onclick="changeImage();">更改圖片</button> </body> </html>
2.2設定標籤的顯示與隱藏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>document的常用操作2</title> </head> <body> <img class="icon" src="./image/img_01.jpg" alt=""> <p id="word">這裡風景很美</p> <p></p> <button>隱藏</button> <script type="text/javascript"> //1.1拿到所有要操作的標籤 var icon = document.getElementsByClassName('icon')[0]; var p = document.getElementById('word'); var btn = document.getElementsByTagName('button')[0]; console.log(icon,p,btn); //1.2監聽按鈕的點選 btn.onclick = function () { if (btn.innerText == '隱藏') { //隱藏 css 屬性 display p.style.display = 'none'; icon.style.display = 'none'; btn.innerText = '顯示'; }else { //隱藏 css 屬性 display p.style.display = 'block'; icon.style.display = 'inline-block'; btn.innerText = '隱藏'; } } </script> </body> </html>