【问题标题】:Auto type inside text input在文本输入中自动输入
【发布时间】:2014-03-28 10:27:34
【问题描述】:

我想让文本自动出现在 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);
});

【问题讨论】:

  • 这里没有免费的代码!展示你到目前为止所做的事情!
  • 聘请开发人员或先了解基础知识。
  • 我没有要求一个完整的脚本来做所有的事情。我只需要一个可以进一步实验的起点。 G先生为我指出了正确的方向,仅此而已。我不是故意要让你们不高兴的。
  • @Wcool:你的问题实际上帮助我解决了我正在解决的问题。赞一个!

标签: javascript jquery html css


【解决方案1】:

试试这样:

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

【讨论】:

  • 非常感谢。我只需要一个起点。通常当我得到一个脚本时,我可以通过实验来解决它。再次感谢。
  • 我现在发布了最终代码。感谢您帮助我走上正轨 Mr.G.
  • @Mr.G:谢谢你的回答
猜你喜欢
  • 2020-12-29
  • 2021-12-06
  • 2017-05-31
  • 2012-11-14
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
相关资源
最近更新 更多