在 HTML 中剪切元素内容时执行脚本?
htmlweb developmentfront end technology更新于 2025/4/10 5:00:17
当用户剪切元素内容时,会触发 oncut 属性。虽然所有 HTML 元素都支持 oncut 属性,但除非元素的 contenteditable 属性设置为"true",否则不允许剪切内容。
以下是示例……
示例:使用 <oncut> 剪切 <input> 中的文本
在下面的示例中,我们将使用 oncut 属性执行 JavaScript 来剪切 <input> 元素中的文本。
<!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>
输出
当您尝试执行脚本时,窗口将弹出并显示"welcome to the 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 函数并显示文本"welcome to the tutorialspoint",当您尝试剪切文本时,它会显示一条警报,提示"您剪切了文本"。
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

