如何将Interval设置为就绪,停止在文本区域聚焦,然后开始在文本区域焦点输出

How to setInterval on ready, stop on textarea focus, then start on textarea focusout?

本文关键字:区域 文本 聚焦 然后 输出 焦点 开始 Interval 设置 就绪      更新时间:2023-09-26

我有一个社交流,我想用setInterval更新它。当有人留下评论或回复时,需要停止SetInterval,否则它会清除文本区域的内容,因为它嵌套在正在更新的内容中。

我正试图使用另一个答案中修改的这段代码,但它失败了,因为它不会在setInterval计时器的第一个周期后停止计时器。

HTML。。。

<div id="social_stream_content">
  <textarea id="comments" rows="4" cols="50" placeholder="Set focus to stop timer"></textarea>
</div>

JS。。。

function auto_load(){
                data = '<textarea id="comments" rows="4" cols="50" placeholder="Set focus to stop timer..."></textarea>';
        $("#social_stream_content").html(data);
        alert("auto_load invoked");
}
var myInterval;
var interval_delay = 10000;
var is_interval_running = false; //Optional
$(document).ready(function(){
    auto_load(); //Call auto_load() function when document is Ready
    //Refresh auto_load() function after 10000 milliseconds
    myInterval = setInterval(interval_function, interval_delay);
    $('textarea').focus(function () {
        console.log('focus');
        clearInterval(myInterval); // Clearing interval on window blur
        is_interval_running = false; //Optional
    }).focusout(function () {
        console.log('focusout');
        clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
        if  (!is_interval_running) //Optional
            myInterval = setInterval(interval_function, interval_delay);
    });
});
interval_function = function () {
     is_interval_running = true; //Optional
     // Code running while textarea is NOT in focus
     auto_load();
}

编辑:我已经更新了代码,以包含在JSfiddle上测试的所有内容。如果在文档就绪时关闭警报后立即将焦点设置为注释文本区域,则计时器将停止。

去除焦点后,间隔计时器的第一个周期完成,计时器将不会再次停止。焦点事件似乎停止了。

这是因为评论文本区域嵌套在正在更新的内容区域中吗?我在拔头发。如果我移除嵌套,它将按预期工作。

我需要注意的是,注释文本区域总是嵌套在社交流的内容div中,原因很明显。

因此,为了进一步更新这个问题:当焦点元素嵌套在更新元素中时,有没有一种方法可以让间隔计时器停止在使用jquery的文本区域焦点上?为什么焦点事件在第一个间隔完成后停止激发?

编辑:完整的JS代码,协同工作,结合Jeremy Klukan的解决方案,适用于任何从事相同类型项目的人。

工作JS:

function auto_load(){
    data = '<textarea id="comments" rows="4" cols="50" placeholder="Set focus to stop timer..."></textarea>';
    $("#social_stream_content").html(data);
    alert("auto_load invoked");
}
var myInterval;
var interval_delay = 10000;
var is_interval_running = false; //Optional
$(document).ready(function(){
    auto_load(); //Call auto_load() function when document is Ready
    //Refresh auto_load() function after 10000 milliseconds
    myInterval = setInterval(interval_function, interval_delay);
    $('body').on('focus', '#social_stream_content textarea', function (event) {
        console.log('focus');
        clearInterval(myInterval); // Clearing interval on window blur
        is_interval_running = false; //Optional
    }).on('focusout', '#social_stream_content textarea', function(event) {
        console.log('focusout');
        clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
        if  (!is_interval_running) //Optional
            myInterval = setInterval(interval_function, interval_delay);
    });
});
interval_function = function () {
     is_interval_running = true; //Optional
     // Code running while textarea is NOT in focus
     auto_load();
}

您可以使用addEventListener检测textarea的焦点和模糊(事件:焦点和模糊)。

您可以使用传递intervalIDclearInterval()来结束setInterval()

下面是一个简单的工作示例,显示了主体(使用普通JavaScript)。

基本上:

  • 页面加载计时器启动时
  • 当用户聚焦textarea计时器停止时
  • 当用户模糊textarea计时器再次启动时

文件:

WindowTimers.clearInterval()

WindowTimers.setInterval()

您还可以找到感兴趣的Document.activeElement.

window.app = {
  timerRef: null,
  timerStart: function() {
    this.timerRef = setInterval(function() {
      //alert("Hello");
      console.log('refresh stream');
    }, 2000);
  },
  timerStop:function(){
      clearInterval(this.timerRef);
  },
  txtAreaListenFocus: function() {
    var txtArea = document.getElementById('txtArea');
    txtArea.addEventListener('focus', function(event) {
       this.timerStop();
      console.log('focus');
    }.bind(this));
  },
  txtAreaListenBlur: function() {
    var txtArea = document.getElementById('txtArea');
    txtArea.addEventListener('blur', function(event) {
      this.timerStart();
      console.log('blur');
    }.bind(this));
  },
  start: function() {
    this.timerStart();
    this.txtAreaListenFocus();
    this.txtAreaListenBlur();
  }
};
window.app.start();
<textarea id="txtArea" rows="4" cols="50">
  Some content here
</textarea>


Jquery版本如下。您可以使用.focuout()和.focusin():

$(document).ready(function(){
window.app = {
  timerRef: null,
  timerStart: function() {
    this.timerRef = setInterval(function() {
      //alert("Hello");
      console.log('refresh stream');
    }, 2000);
  },
  timerStop:function(){
      clearInterval(this.timerRef);
  },
  txtAreaListenFocus: function() {
    $('#txtArea').focusin(function(event) {
       this.timerStop();
      console.log('focus');
    }.bind(this));
  },
  txtAreaListenBlur: function() {
    $('#txtArea').focusout(function(event) {
      this.timerStart();
      console.log('blur');
    }.bind(this));
  },
  start: function() {
    this.timerStart();
    this.txtAreaListenFocus();
    this.txtAreaListenBlur();
  }
};
window.app.start();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txtArea" rows="4" cols="50">
  Some content here
</textarea>


关于您有问题的代码,我已经在下面的工作示例中修复了它。

   $(document).ready(function() {
  var myInterval;
  var interval_delay = 1000;
  var is_interval_running = false; //Optional
  var interval_function = function() {
is_interval_running = true; //Optional
console.log('refresh stream');
// Code running while comment textarea is not in focus
//auto_load();
  };
  //auto_load(); //Call auto_load() function when DOM is Ready
  //Refresh auto_load() function after 1000 milliseconds
  myInterval = setInterval(interval_function, interval_delay);
  $('#textarea').focus(function() {
clearInterval(myInterval); // Clearing interval on window blur
is_interval_running = false; //Optional
  }).focusout(function() {
clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
if (!is_interval_running) //Optional
  myInterval = setInterval(interval_function, interval_delay);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="4" cols="50">
  Some content here
</textarea>

焦点事件停止工作,因为当您的间隔函数触发时,它将替换包含它的DIV的内容,从而使TEXTAREA不再存在。

改为:

$('body').on('focus', '#social_stream_content textarea', function (event) {
  // Focus handler
}).on('focusout', '#social_stream_content textarea', function(event) {
  // Focusout handler
});

这将捕获与选择器"#social_stream_content textarea"匹配的所有焦点和焦点输出事件,而不直接附加到任何一个对象。

我的修复:D

HTML:

<div id="social_stream_content"></div>

jQuery:

var myInterval;
var interval_delay = 1000;
var is_interval_running = false; //Optional
$(document).ready(function(){
    data = '<textarea id="comments" rows="4" cols="50" placeholder="Set focus to stop timer..."></textarea>';
    $(data).appendTo("#social_stream_content");
    //Refresh auto_load() function after 10000 milliseconds
    var myInterval = setInterval(interval_function, interval_delay);
    $('#comments').focus(function () {
        console.log('focus');
        clearInterval(myInterval); // Clearing interval on window blur
        is_interval_running = false; //Optional
    }).focusout(function () {
        console.log('focusout');
        clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
        if  (!is_interval_running) //Optional
            myInterval = setInterval(interval_function, interval_delay);
    });
});
interval_function = function () {
     is_interval_running = true; //Optional
     // Code running while textarea is NOT in focus
     $("#comments").val("");
     console.log("loop");
}

希望能有所帮助。