在 HTML 文件中建立可編輯內容


在 HTML 中,我們可以使用 `contenteditable` 屬性來編輯內容,它指定元素內容是否可由使用者編輯。

`contentEditable` 屬性設定或返回元素內容是否可編輯。

語法

HTML 中可編輯內容的用法/語法為:

<element contenteditable = "true|false">

上述 `contenteditable` 屬性有兩個值:true/false。

  • True 表示元素可編輯。

  • False 表示元素不可編輯。

示例

以下是建立 HTML 中可編輯內容的示例:

<!DOCTYPE html>
<html>
<body>
   <p contenteditable="true">This content is editable. Try to edit it.</p>
   <p>This is a normal content. It won't edit.</p>
</body>
</html>

示例

以下是在另一個示例中將 `contenteditable` 屬性的值更改為 true:

<!DOCTYPE html>
<html>
<head>
   <title>contenteditable attribute</title>
   <style>
      body {
         width: 70%;
         text-align: center;
      }

      h1 {
         color: blue;
      }
   </style>
</head>
<body>
   <h1>TutorialsPoint</h1>
   <h2>Using contenteditable attribute</h2>
   <p contenteditable="true">Tutorials Point: Tutorials Point is a leading Ed Tech company striving to provide the best learning material on technical and non-technical subjects.</p>
</body>
</html>

執行上述示例後,我們可以在一個矩形框中看到一些文字內容。我們還可以編輯矩形框中存在的文字內容,因為 `contenteditable` 屬性的值設定為 TRUE。

示例

如果將 `contenteditable` 屬性的值更改為 false,則無法編輯文字:

<!DOCTYPE html>
<html>
<head>
   <title>contenteditable attribute</title>
   <style>
      body {
         width: 70%;
         text-align: center;
      }

      h1 {
         color: blue;
      }
   </style>
</head>
<body>
   <h1>TutorialsPoint</h1>
   <h2>Using contenteditable attribute</h2>
   <p contenteditable="false">Tutorials Point: Tutorials Point is a leading Ed Tech company striving to provide the best learning material on technical and non-technical subjects.</p>
</body>
</html>

我們無法編輯內容,因為 `contenteditable="false"` 屬性值已設定。

示例

現在讓我們透過應用層疊樣式表 (CSS) 來檢視可編輯內容的示例:

<!DOCTYPE html>
<html>
<head>
   <style>
      .output {
         font: 1rem 'Fira Sans', sans-serif;
      }

      blockquote {
         background: orange;
         border-radius: 5px;
         margin: 16px 0;
      }

      blockquote p {
         padding: 15px;
      }

      cite {
         margin: 16px 32px;
      }

      blockquote p::before {
         content: '\201C';
      }

      blockquote p::after {
         content: '\201D';
      }

      [contenteditable='true'] {
         caret-color: red;
      }
   </style>
</head>
<body>
   <blockquote contenteditable="true">
      <p>Edit this content to add your own Text</p>
   </blockquote>
   <cite contenteditable="true">-- Write your Name Here</cite>
</body>
</html>

更新於:2023年10月6日

606 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告