简体   繁体   English

在文字输入中自动输入

[英]Auto type inside text input

I would like to let there automatically appear text inside an input type=text element. 我想让在输入type = text元素内自动出现文本。

I would like to accomplish that the different kind of texts are stored inside an array and that every 5 seconds or so, a text is 'typed' by javascript into this field. 我想完成的工作是,将不同类型的文本存储在数组中,并且每隔5秒钟左右,JavaScript将文本“键入”到该字段中。 Then I also like that when I focus on the field (to input text in it by keyboard) that it stops auto-typing and shows an empty input element. 然后,当我专注于该字段(通过键盘在其中输入文本)时,它也会停止自动键入并显示一个空的输入元素。

Anybody know how to go about this? 有人知道该怎么做吗? I'm a back-end programmer, but need to do some frontend programming and just haven't had the time to thoroughly learn Javascript. 我是一个后端程序员,但是需要做一些前端编程,而又没有时间充分学习Javascript。 At the moment I only know PHP thoroughly, but would expand my knowledge to css, html and javascript too. 目前,我只完全了解PHP,但是也会将我的知识扩展到CSS,HTML和JavaScript。

Hope somebody is able to help me out :) 希望有人能够帮助我:)

EDIT: This is the solution I came up with and it works. 编辑:这是我想出的解决方案,并且可以工作。 The input field has as ID: searchBar. 输入字段的ID为:searchBar。 The code is not very elegant, but I'm still learning :) Thanks for the answers. 该代码不是很优雅,但我仍在学习:)感谢您的回答。 It helped me a lot. 这对我帮助很大。

var searchBar = document.getElementById('searchBar');

var keywords = ['Auto typed text number 1',
               'This is number 2 auto typed',
               'Yet another auto typed line',
               'The last line before it loops again'];

var index = 0;
var arrCounter = 0;
var focus = false;
var timer1, timer2;

function resetBox() {
    searchBar.value = '';
    index = 0;
    autoType();
}

var autoType = function() {

    if (focus) {

        return;
    }

    if (index <= keywords[arrCounter].length) {
        searchBar.value = keywords[arrCounter].substr(0, index++);
        timer1 = setTimeout("autoType()", 50);
    } else {

        arrCounter++;
        if(arrCounter === keywords.length){
            arrCounter = 0;
        }

        timer2 = setTimeout(resetBox, 5000);
    }
};

autoType();
$("#searchBar").on("focus", function(){
    focus = true;
    searchBar.value = '';
    clearTimeout(timer1);
    clearTimeout(timer2);

}).on("blur", function(){
    setTimeout(function() {
        focus = false;
        resetBox();
    }, 1000);
});

Try like this: 尝试这样:

html html

<input id='demo_input' size='100'/>

javascript: javascript:

var demo_input = document.getElementById('demo_input');

var type_this = "try this example";
var index = 0;

window.next_letter = function() {
    if (index <= type_this.length) {
        demo_input.value = type_this.substr(0, index++);
        setTimeout("next_letter()", 50);
    }
}

next_letter();

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

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