简体   繁体   English

通过键入添加前缀/后缀

[英]Add a prefix/suffix by typing

I have an initially empty input (text) field.我有一个最初为空的输入(文本)字段。 I would like that as soon as someone begins to type (onkeypress??), a prefix/suffix will be autom.我希望一旦有人开始输入(onkeypress??),前缀/后缀将是自动的。 added to the typed string.添加到输入的字符串中。 It should not be possible to delete the prefix/suffix from the final string and it should not be possible that the final string is just the prefix/suffix (in this case the text field should be emptied).应该不可能从最终字符串中删除前缀/后缀,并且最终字符串也不应该只是前缀/后缀(在这种情况下,应该清空文本字段)。

Can someone help me with a (plain) javascript, please?有人可以用(普通的)javascript 帮助我吗?

It is definitely an anti-pattern to modify user input on keypress!在按键上修改用户输入绝对是一种反模式! There are many corner cases that make this annoying to use and hard to test... If the user types very fast, if content is actually copy-pasted, event being triggered by non typing keypress..有许多极端情况使这令人讨厌并且难以测试......如果用户输入非常快,如果内容实际上是复制粘贴的,则事件由非键入按键触发..

The "acceptable" solution IMHO , if you really want this, is to correlate user input with a readonly modified input (or any other element on the UI)! IMHO ,“可接受”的解决方案是将用户输入与只读修改输入(或 UI 上的任何其他元素)相关联!

<input id="uazz" type="text">single<br/><br/>

<input id="in" type="text">in<br/><br/>
<input id="out" type="text" readonly>out<br/><br/>

let userInput = document.getElementById('uazz')

let prefix='@'
let suffix='%'

function transformInput(el){
  let originalInput = el.target.value;
  if(originalInput!==''){
      let transformedInput = originalInput
    if(!transformedInput.match(new RegExp('^' + prefix))){
        transformedInput = prefix + transformedInput
    }
    if(!transformedInput.match(new RegExp(suffix + '$'))){
        transformedInput = transformedInput + suffix
    }
        if(transformedInput!==originalInput){
        el.target.value = transformedInput
    }
  }
}

userInput.onkeyup = transformInput

/* :] */

function transformInputOUT(el){
    let userInputOUT = document.getElementById('out')
  let originalInput = el.target.value;
  let transformedInput = originalInput

  if(transformedInput !== ''){
      transformedInput = prefix + transformedInput + suffix
  }
  userInputOUT.value = transformedInput

}


let userInputIN = document.getElementById('in')
userInputIN.onkeyup = transformInputOUT

See for yourself on this horrible implementation亲眼看看这个可怕的实现
https://jsfiddle.net/6f5zgtqo/5/ https://jsfiddle.net/6f5zgtqo/5/

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

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