如何在javascript中按退格键时防止光标返回

How to prevent the cursor to go back while pressing backspace key in javascript?

本文关键字:返回 光标 javascript      更新时间:2023-09-26

请考虑以下html。

<div id="container" contenteditable="true">
<p>This is a paragraph <span class="test">'this text is inside the span'</span> 
        This is another paragraph afer the span tag inside this p tag
    </p> </div>

如您所见,p 和 span 标记在浏览器中是可编辑的。这意味着我们可以在浏览器中编写。现在我的问题是关于 p 标签内的跨度。所以任何人都可以解释如果光标(在浏览器中输入此范围时)就在 span 标签之后,即在结束 span 标签之后,退格键应该不起作用。

更简单的是,一旦光标超出跨度,退格键不应再次移动它以转到跨度。请帮助JavaScript中的简单示例。

如果你能稍微改变一下你的 DOM,你可以在没有 Javascript 的情况下做到这一点。

看到小提琴

<div id="container">
    <span  contenteditable="true">This is a paragraph</span>
    <span class="test" contenteditable="true">'this text is inside the span'</span>
    <span contenteditable="true">This is another paragraph afer the span tag inside this tag</span>
</div>

CSS只是为了显示不同的跨度

.test
{
    background-color: red;
}