如何在 HTML 中剪下元素內容時執行指令碼?


oncut 屬性在使用者剪下元素內容時觸發。雖然所有 HTML 元素都支援 oncut 屬性,但除非元素的 contenteditable 屬性設定為“true”,否則不允許剪下內容。

以下是一些示例……

示例:使用 <oncut> 剪下 <input> 中的一些文字

在下面的示例中,我們使用 **oncut** 屬性在 <input> 元素中剪下一些文字時執行 JavaScript 程式碼。

<!DOCTYPE html> <html> <body> <input type="text" oncut="myworld()" value="WELCOME TO THE TUTORIALSPOINT"> <p id="varma"></p> <script> function myworld() { document.getElementById("varma").innerHTML = "You cut text....!"; } </script> </body> </html>

輸出

當您嘗試執行指令碼時,將彈出視窗並顯示文字“歡迎來到 tutorialspoint”,當您嘗試剪下輸入內容時,它將顯示文字“您剪下了文字”。

示例:Contenteditable 設定為“true”

在下面的示例中,我們執行 JavaScript 程式碼,在 <p> 元素中剪下一些文字,同時將 contenteditable 設定為“true”。

<!DOCTYPE html> <html> <body> <p contenteditable="true" oncut="myFunction()">WELCOME TO THE TUTORIALSPOINT</p> <script> function myFunction() { alert("You cut text!"); } </script> </body> </html>

輸出

當指令碼執行時,contenteditable 設定為 true 以允許 oncut 函式並顯示文字“歡迎來到 tutorialspoint”,當您嘗試剪下文字時,它將顯示一個警報,提示“您剪下了文字”。

更新於:2022年9月5日

172 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.