gpt4 book ai didi

javascript - Node.js 聊天应用附加样式文本

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:03 26 4
gpt4 key购买 nike

我用 node.js 制作了一个聊天应用程序,客户端在其中输入用户名,然后可以发送消息。它将消息附加到 <ul> 中让其他用户看到:“用户名:消息”。我想将用户名设为粗体和蓝色。如何用最少的代码完成?

HTML(无样式)

<!doctype html>


<html>


<head>

<title>Lucas Chat</title>


</head>



<body>
<div id="top">
<h1>Welcome to the chat!</h1>
<br>
<p>Enter in a nickname and a message to get started</p>
<br>
<p id="drop">Scroll up or down to view newer/older messages</p>

</div>

<ul id="messages">







</ul>


<form action="">

<input id="u" autocomplete="off" placeholder="Nickname"/><input id="m" autocomplete="off" placeholder="Message"/><button>Send</button>
</form>



<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){

if ($('#m').val() != '' && $('#u').val() != '') {

socket.emit('send message', {msg:$('#m').val(),user:$('#u').val()});
$('#u').css("display", "none")
$('#m').css("width", "90%")
$("#u").css("box-shadow", "0px 0px 0px rgba(0, 0, 0, 0)")
$("#m").css("box-shadow", "0px 0px 0px rgba(0, 0, 0, 0)")
$('#m').val('');

} else if ($('#u').val() === '' && $('#m').val() === '') {
$("#u").css("box-shadow", "0px 0px 15px #ff8989")
$("#m").css("box-shadow", "0px 0px 15px #ff8989")
} else if ($('#u').val() === '' && $('#m').val() != '') {
$("#u").css("box-shadow", "0px 0px 15px #ff8989")
$("#m").css("box-shadow", "0px 0px 0px rgba(0, 0, 0, 0)")
} else if ($('#m').val() === '' && $('#u').val() != '') {
$("#m").css("box-shadow", "0px 0px 15px #ff8989")
$("#u").css("box-shadow", "0px 0px 0px rgba(0, 0, 0, 0)")
}

return false;
});
socket.on('receive message', function(msg){
$('#messages').append($('<li>').html(msg));
});
</script>



</body>
</html>

JS

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var peopleCount = 0;

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){

peopleCount++

console.log('a user connected | connections: ' + peopleCount)

socket.on('disconnect', function(){

peopleCount--

console.log('a user disconnected | connections: ' + peopleCount)

});
});


io.on('connection', function(socket){
socket.on('send message', function(data){
io.emit('receive message', data.user + ': ' + data.msg);
});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

最佳答案

var username = "<span style='font-weight:bold;color:blue;'>"+$('#u').val()+"</span>";

socket.emit('send message', {msg:$('#m').val(),user:username});

关于javascript - Node.js 聊天应用附加样式文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37441020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com