JavaScript-焦点事件停止计时器

JavaScript-焦点事件停止计时器,javascript,Javascript,我有一个脚本,每2秒更改文本框中的文本。我想让它停止(计时器)并在用户单击并关注文本框时清除文本框 var text = ["1", " 2", "3"]; var counter = 0; var elem = document.getElementById("txt1"); setInterval(change, 2000); function change() { document.getElementById("txt1").value = text[counter]; //data

我有一个脚本,每2秒更改文本框中的文本。我想让它停止(计时器)并在用户单击并关注文本框时清除文本框

var text = ["1", " 2", "3"];
var counter = 0;
var elem = document.getElementById("txt1");

setInterval(change, 2000);

function change() {
document.getElementById("txt1").value = text[counter]; //data is the element
    counter++;
    if(counter >= text.length) { 
        counter = 0; 
    }
}

更新您的输入类型,如

 <input type="text" onfocus="myFunction()">

在脚本中添加myFunction

function myFunction(){
   clearInterval(tt);
   document.getElementById("txt1").value = "";
}
试试这个:

//当你设定时间间隔时

区间\变量=设定区间(变更,2000年)

//当您要停止执行“更改”时


clearInterval(interval_变量)

调用
setInterval()时存储间隔id

然后在
focus()
处理程序中取消它:

function stopit()
{
  if (interval) {
    clearInterval(interval);
    interval = false;
    elem.value = "";
  }
}

if (elem.addEventListener) {
  elem.addEventListener('focus', stopit, false); 
} else if (elem.attachEvent)  {
  elem.attachEvent('onfocus', stopit);
}
请注意,
stopit()
只清除间隔(和文本)一次——这样,如果用户键入内容,在别处聚焦,然后重新聚焦,我们不会放弃他们的输入


示例:

真正简单的解决方案是只检查输入是否在函数中有焦点,并且
document.activeElement
保存焦点元素,因此只需将其与
elem
进行比较并返回它们是否相同即可

var text    = ["I want a smartphone with a big screen", "I don't want a smartphone made by a korean company", "I want a LED TV with high refresh rate"];
var counter = 0;
var elem    = document.getElementById("txt1");

elem.addEventListener('focus', function() {this.value=''}, false);

setInterval(change, 2000);

function change() {
    if (document.activeElement == elem) return;

    elem.value = text[counter];
    counter++;
    if(counter >= text.length) { counter = 0; }
}

示例2,在调用
clearInterval(tt)
后,调用
document.getElementById(“txt1”).value=“”谢谢回答!谢谢回答:)
var interval = setInterval(change, 2000);
function stopit()
{
  if (interval) {
    clearInterval(interval);
    interval = false;
    elem.value = "";
  }
}

if (elem.addEventListener) {
  elem.addEventListener('focus', stopit, false); 
} else if (elem.attachEvent)  {
  elem.attachEvent('onfocus', stopit);
}
var text    = ["I want a smartphone with a big screen", "I don't want a smartphone made by a korean company", "I want a LED TV with high refresh rate"];
var counter = 0;
var elem    = document.getElementById("txt1");

elem.addEventListener('focus', function() {this.value=''}, false);

setInterval(change, 2000);

function change() {
    if (document.activeElement == elem) return;

    elem.value = text[counter];
    counter++;
    if(counter >= text.length) { counter = 0; }
}