iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0

Day 7
大家好,我是Karin。今天要來完成HTML DOM觀念實作練習。
參考影片:彭彭的課程
https://www.youtube.com/watch?v=8OejlO7N_vw

認識內建的window物件(HTML DOM結構的最上層)

console.log(window);

window物件內容極龐大,代表著整個網頁的結構,包含所有物件及方法。以下顯示其中小一部分
https://ithelp.ithome.com.tw/upload/images/20240907/20168967WGP5fJgCBR.png

取得視窗、螢幕尺寸的寬與高

<!DOCTYPE html>
<html>
<head> 
</head>
<body>
    <script>
        //取得視窗寬、高
        console.log(window.innerWidth,window.innerHeight); 
        //(透過screen物件)取得螢幕寬、高
        console.log(window.screen.width,window.screen.height); 
    </script>
</body>
</html>

更改網址列的內容(跳轉網頁)

<!DOCTYPE html>
<html>
<head> 
</head>
<body>
    <script>
        //取得網址
        console.log(window.location.href);
        //更改網址(製作跳轉網頁)
        window.location.href="https://ithelp.ithome.com.tw/2024ironman/"
    </script>
</body>
</html>

執行後就會發現網頁直接被跳轉到2024iThome鐵人賽的畫面了(且無法返回上一頁)。

認識document物件

<!DOCTYPE html>
<html>
<head> 
</head>
<body>
    <script>
        console.log(window.document);
        console.dir(document);
    </script>
</body>
</html>

以下圖片顯示兩種取得方法的差異
https://ithelp.ithome.com.tw/upload/images/20240907/201689678luWaDFFfG.png

更改網頁標題

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM Concept</title> 
</head>
<body>
    <script>
        //取得網頁標題
        console.log(document.title);
        //更改網頁標題
        document.title="NewTitle"
    </script>
</body>
</html>

可以看到console中會顯示舊的網頁標題
https://ithelp.ithome.com.tw/upload/images/20240907/201689675LdyAtYQpV.png
而NewTitle取而代之成為新的網頁標題
https://ithelp.ithome.com.tw/upload/images/20240907/20168967Jh0x33BW3Q.png

更改主畫面的內容(Body標籤的內文:innerHTML)

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM Concept</title> 
</head>
<body>
    <script>
        //取得主畫面的內容
        console.log(document.body.innerHTML);
        //更改主畫面的內容
        document.body.innerHTML="Hello";
    </script>
</body>
</html>

可以看到console中會顯示原本程式碼中所有包含在 body 中的內文
https://ithelp.ithome.com.tw/upload/images/20240907/20168967U4xV2ajdRG.png
而後Hello會取代所有內文,直接顯示在主畫面上
https://ithelp.ithome.com.tw/upload/images/20240907/20168967bdcKJjnUfl.png


上一篇
Day 6 HTML DOM核心觀念
下一篇
Day 8 HTML DOM 網頁畫面操作演練
系列文
每天都進步一點!從零開始的JavaScript 與基礎網路知識學習26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言