【问题标题】:Changing background color of div in chat box with every message使用每条消息更改聊天框中 div 的背景颜色
【发布时间】:2015-08-03 02:41:36
【问题描述】:

我有一个公共聊天室,所有用户都可以在其中输入消息,其他人也可以看到这些消息。我有一种情况,假设我在聊天框中输入了一条消息,然后 div 的 bg-color 变为红色,下一条消息变为白色。此外,如果任何其他用户在公共聊天框中发送任何消息,并假设 div 的最后一个背景颜色是白色,那么它应该是所有人都能看到的红色。简而言之,我需要使用该公共聊天框中的任何用户发送的每条消息来更改 div 的 bg 颜色。结果应该类似于所附的屏幕截图。这可以在时间戳的帮助下实现吗?如果是的话怎么做?

这是我用 jQuery 更新的简单 HTML div:

<div id="wrapper">
            <div class="bubble-container" ></div>
</div>

这是我的样式表 CSS:

.bubble-container
{
    display: none;
    width: 100%;
    height: 50px;
}

.bubble
{
    display: inline-block;
    position: relative;
    clear: both;
    background-color: #ffffff;
    width: 100%;
}


.bubble-text
{
    height: 50px;
    display:table;
    margin-left: 10px;
}

.bubble-text p
{
    display: table-cell; 
    vertical-align: middle; 
    font-size:16px;
    margin-left: 10px;
}

用户输入并在 UI 上显示的消息的 JQuery 代码。我正在使用 websockets 来制作这个聊天应用程序。

函数的逻辑工作正常。但我认为你会感兴趣的部分是我设计 div 的方式。到目前为止,对于每条消息,此代码都有一个白色的 bg div。但我需要改变它。

function onMessage(evt) {
    var msgText = evt.data;
    var bubble = $('<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>' + msgText + '</p></div></div>');
    var bubbles = 1;
    var maxBubbles = 8;
    var server;
    //var bubble = text;
    $("#msgText").val("");

    $(".bubble-container:last")
        .after(bubble);

    if (bubbles >= maxBubbles) {
        var first = $(".bubble-container:first")
            .remove();
        bubbles--;
    }

    bubbles++;
    $('.bubble-container').show(250, function showNext() {
        if (!($(this).is(":visible"))) {
            bubbles++;
        }

        $(this).next(".bubble-container")
            .show(250, showNext);

        $("#wrapper").scrollTop(9999999);
    });

}

【问题讨论】:

  • 请为聊天框发布一些代码或您尝试过的代码
  • @CodingEnthusiast 我添加了一些代码,但这不是它的工作方式,因为它显示在我附加的屏幕截图中。但这就是我希望它工作的方式。

标签: javascript jquery html


【解决方案1】:

使用 CSS:

.bubble-container:nth-child(even) {
  background: red;
}
<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>msg#1</p></div></div>
<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>msg#2</p></div></div>
<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>msg#3</p></div></div>
<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>msg#4</p></div></div>
<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>msg#5</p></div></div>
<div class="bubble-container"><span class="bubble"><div class="bubble-text"><p>msg#6</p></div></div>

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多