繁体   English   中英

如何停止退格或删除键以删除光标前的文本

[英]How to stop backspace or delete key to delete text before the cursor

如果输入类型 text 之前的单词是“Hi Harry”,我试图阻止光标删除它之前的单词。 我试图限制光标删除文本,如果用户在它匹配“嗨哈利”之前开始删除文本和文本然后停止删除此文本。 用户也不应该通过选择和键入另一个字符来覆盖“Hi Harry text”。 用户不得通过任何操作删除或替换“Hi Harry”。

任何满足要求的解决方案都可能有所帮助。

.html

<input id="target" type="text" value="Hi Harry"> 

js

$( "#target").keydown(function(e) {
   if (e.which == 8 && e.target.value === "Hi Harry") { 
    // backspace or delete key

            return false;  

// here I want to stop cursor from deleting if user started deleting text and 
//text before it if matches "Hi Harry" then stop deleting this text.
        }

    });

当满足这些条件时,您可以调用传递给回调函数的event参数的preventDefault方法:

  • 正在按下BACKSPACE ( e.which === 8 )。
  • input的值当前等于Hi Harry

更好的方法是存储input的初始值,这样您就可以将任何内容写入其初始值。

 const inp = $("#target"), /** referening the input **/ initVal = inp.val(); /** store its initial value **/ /** keydown event handler **/ inp.on('keydown', e => { e.which == 8 && inp.val() == initVal && e.preventDefault(); /** * backspace and current value is the same as the initial value then just don't allow the backpace functionnality at this moment. * if the conditions aren't met, simply the line won't work thus allow inputing. **/ });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="target" type="text" value="Hi Harry">

正如您现在可能知道的,为了防止用户使用退格键delete 删除,您可以在e.which == 8e.which == 46的事件上 preventDefault 。

如果用户选择文本或在“嗨哈利?”之间点击怎么办? 您还需要处理一些文本选择事件。 请参阅下面的片段[1]

 // monitor key down function var initialValue = $("#target").val(); $("#target").keydown(function(e) { if (e.target.selectionStart < initialValue.length) { //prevent user from typing stuff in between "Hi Harry" e.preventDefault(); return; } if ((e.which == 8 || e.which == 46) && e.target.value === initialValue) { // backspace or delete key // backspace is 8, delete is e.preventDefault(); } }); // monitor text selection and force to deselect function handleSelections(e) { e.preventDefault(); var endPoint = initialValue.length; if (e.target.selectionEnd > initialValue.length + 1) { endPoint = e.target.selectionEnd; } if (e.target.selectionStart < initialValue.length) { e.target.setSelectionRange(initialValue.length, endPoint); }; } // prevent any selection of text until after "Hi Harry" $("#target").get(0).addEventListener('select', handleSelections); // prevent cursor positioning anywhere within "Hi Harry" $("#target").get(0).addEventListener('click', handleSelections);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="target" type="text" value="Hi Harry">

[1]在 Google Chrome 78 上测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM