繁体   English   中英

在文字输入中自动输入

[英]Auto type inside text input

我想让在输入type = text元素内自动出现文本。

我想完成的工作是,将不同类型的文本存储在数组中,并且每隔5秒钟左右,JavaScript将文本“键入”到该字段中。 然后,当我专注于该字段(通过键盘在其中输入文本)时,它也会停止自动键入并显示一个空的输入元素。

有人知道该怎么做吗? 我是一个后端程序员,但是需要做一些前端编程,而又没有时间充分学习Javascript。 目前,我只完全了解PHP,但是也会将我的知识扩展到CSS,HTML和JavaScript。

希望有人能够帮助我:)

编辑:这是我想出的解决方案,并且可以工作。 输入字段的ID为:searchBar。 该代码不是很优雅,但我仍在学习:)感谢您的回答。 这对我帮助很大。

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);
});

尝试这样:

html

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

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