HTML5聊天界面代碼是一種用于創建實時聊天室的編程技術。采用HTML5聊天界面代碼可以使網頁更加現代化、互動化并且易于操作。以下是一個HTML5聊天界面代碼的范例:
<!DOCTYPE html>
<html>
<head>
<title>聊天室</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}
#chat-window {
display: flex;
flex-direction: column;
height: 600px;
width: 400px;
border: 2px solid black;
}
#message-box {
display: flex;
flex-direction: column-reverse;
height: 90%;
padding: 10px;
overflow-y: scroll;
}
#input-box {
height: 10%;
padding: 10px;
display: flex;
}
#input-field {
flex-grow: 1;
margin-right: 10px;
}
#send-button {
width: 100px;
}
.message {
margin-bottom: 10px;
}
.from-user {
background-color: lightgray;
align-self: flex-end;
}
.from-others {
background-color: white;
}
.username {
font-weight: bold;
margin-right: 10px;
}
</style>
</head>
<body>
<div id="chat-window">
<div id="message-box"></div>
<div id="input-box">
<input id="input-field" type="text">
<button id="send-button">發送</button>
</div>
</div>
<script>
const chatWindow = document.querySelector("#chat-window");
const messageBox = document.querySelector("#message-box");
const inputField = document.querySelector("#input-field");
const sendButton = document.querySelector("#send-button");
let username = prompt("請輸入你的用戶名");
function sendMessage() {
let message = inputField.value;
inputField.value = "";
let div = document.createElement("div");
div.classList.add("message", "from-user");
let nameSpan = document.createElement("span");
nameSpan.classList.add("username");
nameSpan.innerHTML = username + ":";
let messageSpan = document.createElement("span");
messageSpan.innerHTML = message;
div.appendChild(nameSpan);
div.appendChild(messageSpan);
messageBox.appendChild(div);
}
sendButton.addEventListener("click", sendMessage);
inputField.addEventListener("keydown", function (event) {
if (event.keyCode === 13) {
sendMessage();
}
});
</script>
</body>
</html>
上述代碼使用了HTML5的一些新特性,包括flex布局、input元素的type屬性、meta標記、const變量等。JS部分則是定義了一個函數用于發送消息,并且添加了事件監聽器來響應用戶輸入,實現了實時聊天的功能。如果可以配合后端編程語言與框架,就可以實現更加完善的聊天室服務了。