模拟传入消息通知

Simulate incoming message notification

本文关键字:通知 消息 模拟      更新时间:2023-09-26

这有点难以解释。。

我正在尝试通知用户正在"键入"一条"消息"。然而,这是来自函数中某个参数的预设消息。

考虑到消息是如何预设的,我正试图根据函数中传递的"消息"的长度按比例缩放"传入消息动画"和消息延迟时间,以模拟用户在另一端打字(3句话的消息立即出现是没有意义的,3个字的消息在30秒后出现也是没有意义的)

我加入了一把小提琴,以更好地说明我的目标。。。现在它只检查消息的长度是否为24个字符;"else if"目前是我努力实现的目标的持有者。

http://jsfiddle.net/ducFh/1/

jquery

function communicate(dialog) {
    if (dialog.length === 24) {
        messageIcon(3);
        setTimeout(function() {
            callExample(dialog);
        }, 2500);
    } else if (dialog.length > 24) {
        alert('oops');
    }
}
function messageIcon(time) {
    $('#infoBox').append("<span class='icon'>...</span>");
    for (i=0;i<time;i++) {
        $('.icon').fadeIn('fast');
        $('.icon').fadeOut('slow');
        if (i === time) {
            $('#infoBox .icon').remove();           
        }
    }
}
function callExample(message) {
    $('#infoBox').append("<span>example &gt; "+message+"</span>");
}
communicate("this is only an example.");

利用JS是一种函数式语言这一事实。JQuery动画在动画完成时调用回调函数(.fadeIn())。

我的方法(确保图标可见时消息永远不会出现)是将等待图标和消息显示结合在一起,在图标充分闪烁后显示消息

http://jsfiddle.net/ducFh/2/

function communicate(dialog) {
    // dividing by 8 because the icon was flashed 3
    // times in original code for a 24 character message.
    // But really this can be anything you want. Anything ;-)
    var iterations = dialog.length / 8;
    $('#infoBox').append("<span class='icon'>...</span>");
    // This method just makes the next method easier to read
    // It flashes the given jQuery selection once and then
    // calls the callback
    function fadeInThenOut(jq, callback) {
        jq.fadeIn('fast', function () {
            jq.fadeOut('slow', callback);
        });
    }
    // This function flashes the icon `iterationsToCome`-times
    // After it has finished it calls the callback.
    // Recursion is used to make this thing asynchronous (required
    // by the use of jQuery animations).
    function flashIcon(iterationsToCome, callback) {
        fadeInThenOut($('.icon'), function () {
            // classic pattern of recursive functions
            if (iterationsToCome > 0) {
                flashIcon(iterationsToCome - 1, callback);
            } else {
                callback();
            }
        });
    }
    flashIcon(iterations, function () {
        $('#infoBox .icon').remove();
        // provoke some additional delay for the last
        // wait. could also be removed, and the append()
        // called immediately.
        window.setTimeout(function () {
            $('#infoBox').append("<span>example &gt; " + dialog + "</span>");
        }, 100);
    });
}
communicate("this is only an example.");

请注意,我正在大量使用基于函数的变量和闭包的作用域。如果你不知道这一点,你应该找一本关于JavaScript的好书;-)当然,如果您对代码有任何疑问,请随时询问。

将时间乘以消息长度怎么样?即CCD_ 1(要调整的数目)。为了避免长消息的超长时间,您可以使用日志功能,即:Math.round(Math.log(dialog.length) * ...)