简体   繁体   English

使用 vanilla JavaScript 模拟选项卡和输入键

[英]Emulate tab and enter key using vanilla JavaScript

I have a situation where I need to focus on input/textarea/contenteditable elements.我有一种情况需要关注 input/textarea/contenteditable 元素。 Then set the values programmatically.然后以编程方式设置值。 After that I need to emulate tab or enter programmatically so that entered text can look like tags as show in below picture.之后,我需要模拟选项卡或以编程方式输入,以便输入的文本看起来像标签,如下图所示。

can anybody suggest how can this be achieved?有人可以建议如何实现这一目标吗?

Just like below demo, I have a input field.就像下面的演示一样,我有一个输入字段。 I have added blur for the demonstration purpose but I want tab or enter events to be fired.我为演示目的添加了模糊,但我想要触发 tab 或 enter 事件。 I know that blur will do the trick but I dont want that.我知道模糊会起作用,但我不想要那样。

Demo: http://jsfiddle.net/2np1cwe6/ Vanilla JS code: http://jsfiddle.net/dyc4bLta/演示: http : //jsfiddle.net/2np1cwe6/原版 JS 代码: http : //jsfiddle.net/dyc4bLta/

在此处输入图片说明

$('input').tagsinput({
  typeahead: {
    source: ['Amsterdam', 'Washington', 'Sydney', 'Beijing', 'Cairo']
  },
  freeInput: true
});
$('input').on('itemAdded', function(event) {
    setTimeout(function(){
        $(">input[type=text]",".bootstrap-tagsinput").val("");
    }, 1);
});

var i = $('input');
setTimeout(function() {
  i.focus()
    i.val('adfasdfasd');
}, 2000);

setTimeout(function() {
  i.blur()
}, 8000);

Manipulate the following as per your need.根据您的需要操作以下内容。 This will recognize a tag/word when you enter a comma.当您输入逗号时,这将识别标签/单词。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <textarea id="text"></textarea>
  <div id="tags">
  </div>
  <script>
    let text = document.querySelector("#text");
    let tags = []
    text.addEventListener("keyup", (e)=>{
      if(text.value[text.value.length-1]==',')
        {
          tags.push(text.value.substr(0, text.value.length-1));
          text.value = "";
          let out = "";
          tags.forEach(tag=>{
            out += tag + " ";
          });
          document.getElementById("tags").innerHTML=out;
        }
    });
  </script>
</body>
</html>

You can pass the characters that act as confirmation to the tagsinput function using the confirmKeys array key.您可以使用confirmKeys数组键将作为确认的字符传递给tagsinput函数。 Something like this:像这样的东西:

$('input').tagsinput({
    // Your other configuration array keys here,
    confirmKeys: [8, 13, 32, 44] // 8 = tab, 13 = enter, 32 = space and 44 = ,
});

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

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