如何在 HTML 中使用 contenteditable div 建立自定義插入點?
本文將介紹如何在 HTML 中使用 **contenteditable** div 建立自定義插入點。讓我們深入瞭解如何在 HTML 中使用 **contenteditable** div 建立自定義插入點。
HTML 中的 contenteditable div
**contenteditable** 全域性屬性是一個列舉屬性,它指定元素是否應該可由使用者編輯。在這種情況下,瀏覽器會更改其視窗小部件以啟用編輯。
語法
以下是 **contenteditable** 的語法:
<element contenteditable="true|false">
為了更好地理解如何在 HTML 中使用 **contenteditable div** 建立自定義插入點,讓我們來看以下示例
示例
在下面的示例中,我們執行一個指令碼來使用 **contenteditable div** 建立自定義插入點。
<!DOCTYPE html> <html> <body style="background-color:#D5F5E3 "> <div id="editable" contenteditable="true"> Welcome <br>To The <br>TutorialsPoint </div> <button id="button" onclick="insertionpoint()">Click</button> <script> function insertionpoint() { var tutorial = document.getElementById("editable") var range = document.createRange() var select= window.getSelection() range.setStart(tutorial.childNodes[2], 5) range.collapse(true) select.removeAllRanges() select.addRange(range) 5. How Do You Make A Custom Insertion Point With a Contenteditable Div In HTML } </script> </body> </html>
指令碼執行後,它將在網頁上生成包含文字和點選按鈕的輸出。當用戶點選按鈕時,文字將獲得焦點,允許使用者插入或更改文字。
示例
請考慮以下示例,我們在此執行指令碼以使用 **contenteditable** div 建立自定義插入點。
<!DOCTYPE html> <html> <body style="background-color:#D6EAF8 "> <div class="element" contenteditable="true">MSD</div> <p class="element" contenteditable="true">Virat Kohli</p> <script> document.addEventListener('keydown', event => { if (event.key === 'Enter') { document.execCommand('insertLineBreak') event.preventDefault() } }) </script> </body> </html>
執行上述指令碼後,將彈出輸出視窗,在網頁上顯示文字。當用戶點選文字時,它將獲得焦點,並允許使用者進行更改。
示例
執行以下簡單程式碼,觀察我們如何使用 **contenteditable** div 建立自定義插入點。
<!DOCTYPE html> <html> <body style="background-color:#E8DAEF "> <style> div.tutorial { margin: 30px; } div.display { display:inline-block; background-color: #ABEBC6 ; color: black; width: 300px; } div.container { -webkit-user-select: none; } .invisible { visibility: hidden; } </style> <div class="tutorial"> <div class="container"> <span class="invisible"></span><div class="display" contenteditable="true"> MSD </div> <div class="display" contenteditable="true"> MAHI </div> </div> <div class="unrelated">Mahendra Singh Dhoni is an Indian former<br> international cricketer who was captain of the Indian national cricket team </div> </div> </body> </html>
指令碼執行後,它將生成文字以及在網頁上以綠色顯示的可編輯文字。當用戶點選文字時,它允許使用者插入或更改文字。
廣告