Peiyun Lee
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ###### tags: `前端技能樹` # 互動吧網頁 — Javascipt的DOM 操作 / 事件 在前一篇,我們介紹完 Javascript 的語法和基本功能,包括宣告變數、條件陳述式、函式、物件陣列 ... 等等,接下來就來了解如何透過Javascipt操作,讓網頁互動起來。 ### 什麼是DOM? DOM(文件物件模型,Document Object Model),提供了一套讓 HTML、XML 文件結構化的表示法,**而每個檔案最後都會形成一種DOM樹狀結構**,比如一個 HTML 文件就會形成類似下圖的樣子: ![](https://i.imgur.com/OSeTkbo.png) ## DOM API **DOM 定義了一些屬性方法,讓程式可以存取並改變文件架構和內容**,再結合 Javascript 的使用,就能從 HTML 文件的入口 ```Document``` 往下取得指定的 DOM 節點,來修改該元素的結構、內容、樣式。 ### 取得網頁元素 首先根據HTML標籤 ```tag```、```id```、```class``` 的名稱,取得對應的元素進行操作: ```javascript= // 找到所有 <p> 元素。 document.getElementsByTagName("p"); // 找到 id 為 'id_name' 的元素。 document.getElementById('id_name'); // 找到所有 class 名稱為 'class_name' 的元素。 document.getElementsByClassName('class_name'); ``` ### 修改 HTML 內容 取得節點之後,就可以針對各種屬性去修改 HTML 的內容,比如 ```innerHTML```、```classList```、```setAttribute``` ... 等等。 - **```element.innerHTML```**:取得或設定元素內HTML的內容 ```javascript= let myDiv = document.getElementById("myDiv"); myDiv.innerHTML = "<p>Hello</p>"; ``` ![](https://i.imgur.com/pnuV4JI.png) - **```element.classList```**:讀取該元素的 Class 屬性,另外可以透過定義的一些方法修改該屬性,比如 ```add()```、```remove()```、```toggle()```。 ```javascript= //取得元素 <div id="myDiv" class="default-class"> let myDiv = document.getElementById("myDiv"); //新增class myDiv.classList.add("class1"); //class="default-class class1" //移除class myDiv.classList.remove("class1"); //class="default-class" //如果指定的class不存在則添加、存在則移除 myDiv.classList.toggle("class1"); //class="default-class class1" myDiv.classList.toggle("class1"); //class="default-class" ``` - **```element.setAttribute()```**:設定元素的屬性值。如果屬性已經存在則更新;不存在則添加。另外還可以透過 **```element.getAttribute()```** 取得當前的屬性值。 ```javascript= //取得元素 <a id="myLink" class="default-class"> let myLink = document.getElementById("myLink"); //設定該 Element 的 href 屬性 myLink.setAttribute("href","https://ithelp.ithome.com.tw/2021ironman/event"); //<a href="https://ithelp.ithome.com.tw/2021ironman/event" ...> //設定該 Element 的 class 屬性 myLink.setAttribute("class","red"); //<a class="red" ...> ``` ### 修改 Style 樣式 除了可以針對網頁結構、內容去做調整,還可以利用 **```element.style.cssproperty```** 為對應的元素新增指定的樣式: ```javascript= //修改 #p1 元素的字體顏色 document.getElementById("p1").style.color = "blue"; //修改 #p2 元素的背景顏色 document.getElementById("p2").style.backgroundColor = "blue"; //修改 #p2 元素的字體大小 document.getElementById("p3").style.fontSize = "24px"; ``` ![](https://i.imgur.com/4LnigH5.png) ## 事件處理 當使用者對網頁進行操作,比如點擊按鈕、輸入文字...等等,網頁要根據這些事件(Event)去產生對應的更新。DOM 就定義了各種事件型態,讓我們可以透過 Javascript 進行事件的處理。 ### 事件監聽器(EventListener) 負責事件處理的程式要如何連結到對應的元素上?**通常會使用 ```addEventListener()``` 將事件監聽器(EventListener)註冊到指定的元素上**,當監聽到指定的事件發生時,就執行對應的任務函式。 ```javascript= let button = document.getElementById("btn"); button.addEventListener('click', function (event) { //按下 button 執行 alert('Click'); }); ``` ### 常用的事件 事件|描述| --|-- click|滑鼠點擊物件時 keydown|按下鍵盤按鍵時 mousedown|按下滑鼠按鍵時 mousemove|滑鼠移動時 mouseout|滑鼠離開指定元素四周時 submit|按下送出按鈕時 ## 小結 Javascript 的介紹到這邊就告一個段落囉,當然不只有這些功能,還有很多東西值得探討並研究,並且它也在持續更新中。除了可以看文件、書籍、技術文章進行深入學習之外,**要熟練 Javascript 很好的方式就是直接實作各種想要的功能,在過程中查找資料、解決錯誤來累積知識。** 在下一篇文章會提到如何使用 Bootstrap 快速地建立響應式網站,那我們就下章再見囉! 如果文章中有錯誤的地方,要麻煩各位大大不吝賜教;喜歡的話,也要記得幫我按讚訂閱喔❤️ ### 參考資料 - [MDN - Document](https://developer.mozilla.org/zh-TW/docs/Web/API/Document) - [w3schools - Javascript](https://www.w3schools.com/js/default.asp) - [MDN - Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) - [MDN - Event](https://developer.mozilla.org/zh-TW/docs/Web/API/Event)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully