在焦点事件上停止计时器

JavaScript - stop timer on focus event

本文关键字:计时器 焦点 事件      更新时间:2023-09-26

我有一个脚本,每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()">

也更新

setInterval(change, 2000);

var tt=setInterval(change, 2000);

在脚本中添加myFunction

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

存储调用setInterval()时的间隔id:

var interval = setInterval(change, 2000);

,然后在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()只清除间隔(和文本)一次——这样,如果用户键入某些内容,关注其他地方,然后重新关注,我们不会丢弃他们的输入。

示例:http://codepen.io/paulroub/pen/AtxEr

试试这个:

//设置时间间隔

interval_variable = setInterval(change, 2000);

//当你想停止执行"change"

clearInterval (interval_variable);

真正简单的解决方案是检查输入是否在函数内具有焦点,并且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; }
}

小提琴