在文本输入中自动键入 [英] Auto type inside text input

查看:31
本文介绍了在文本输入中自动键入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让在 input type=text 元素中自动出现文本.

I would like to let there automatically appear text inside an input type=text element.

我想实现将不同类型的文本存储在一个数组中,并且每隔 5 秒左右,javascript 将文本输入"到该字段中.然后我也喜欢当我专注于该字段(通过键盘在其中输入文本)时,它会停止自动输入并显示一个空的输入元素.

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. 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.

有人知道怎么做吗?我是一名后端程序员,但需要做一些前端编程,只是没有时间彻底学习 Javascript.目前我只了解 PHP,但也会将我的知识扩展到 css、html 和 javascript.

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. At the moment I only know PHP thoroughly, but would expand my knowledge to css, html and javascript too.

希望有人能够帮助我:)

Hope somebody is able to help me out :)

这是我想出的解决方案,并且有效.输入字段的 ID 为:searchBar. 代码不是很优雅,但我仍在学习 :) 感谢您的回答.这对我帮助很大.

This is the solution I came up with and it works. The input field has as 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);
});

推荐答案

试试这个:

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

这篇关于在文本输入中自动键入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆