我有一个聊天应用程序,当用户在TEXTAREA字段中输入文本以在他的名字下添加文本时,我创建了一个聊天应用程序,例如输入...但出于个人原因,我喜欢这个“打字...”只出现一次,而不对每个字符重复。我尝试使用one ()函数,但只有当用户重新加载页面时,它才能再次工作。
$("textarea").one('input', function () {
HERE IS MY CODE TO ADD "TYPING.." UNDER HIS NAME
});
function sendMessage() {
HERE IS MY CODE TO DELETE "TYPING..." FROM UNDER HIS NAME
}
我怎么才能让它工作呢?
发布于 2020-02-29 23:52:22
您可以使用一种throttling,使用以下setTimeout
-based函数:
// Returns a function that will call its callback argument
// only when a certain delay has passed. Another callback
// can be called to notify that the delay has expired
function throttle(f, milliseconds, ready = () => null) {
let timer = -1;
return function () {
if (timer === -1) f();
clearTimeout(timer);
timer = setTimeout(function () {
timer = -1;
ready();
}, milliseconds);
}
}
function sendMessage(msg) {
$("div").text("typing...");
}
function clearMessage() {
$("div").text("");
}
$("textarea").on('input', throttle(sendMessage, 3000, clearMessage));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
<div></div>
“打字...”如果在3秒内没有键入,则消息将被清除。如果再次开始键入,则将再次发送/显示消息。在清除消息之前,不会再次发送该消息。
发布于 2020-02-29 23:42:08
您可以使用超时,这将在特定时间后恢复键入状态。在用户继续键入时清除超时。
const textArea = document.querySelector('.area')
const indicator = document.querySelector('.indicator')
let timeout = null
textArea.addEventListener('input', function() {
clearTimeout(timeout)
indicator.innerText = 'Typing...'
timeout = setTimeout(function() {
indicator.innerText = ''
}, 300)
})
.area,
.indicator {
display: block;
margin: 1rem;
}
<textarea class="area"></textarea>
<span class="indicator"></span>
https://stackoverflow.com/questions/60466667
复制相似问题