网站建设常用的英文seo博客网址
题八:滚动弹幕
要求:
1.页面上漂浮字体大小不一、颜色不一,从左向右滚动的弹幕;
2.底部中间有一个发送功能,可以发送新的弹幕;
3.底部的发送部分可以向下收起和弹出。
原理:
- 首先写出弹幕的大小,颜色,等,!!一定要return,不然出不来。
- 要实现左移要不断加速度,当位置大于屏宽时,关闭定时器并移除弹幕。
- 在输入框中的文本传值时,调用createDanmuElement和滚动弹幕函数。
- 主要是靠公式:Math.floor(Math.random() * n ) + 1
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#danmu-container {position: relative;width: 100%;height: 400px;border: 1px solid #ccc;}#down {position: fixed;bottom: 0;left: 0;width: 100%;background-color: #f0f0f0;padding: 10px;display: flex;justify-content: center;align-items: center;transition: all 0.3s ease;}#down.hidden {bottom: -50px;}#message-input {width: 300px;padding: 5px;margin-right: 10px;}#send {padding: 5px 10px;}#up {position: absolute;bottom: 10px;left: 10px;}</style>
</head>
<body><body><div id="danmu-container"></div><div id="down"><input type="text" id="message-input" placeholder="请发送一条友善的弹幕吧!"><button id="send">发送</button></div><button id="up">收起/弹出</button><script>const danmuContainer = document.getElementById('danmu-container');const Down = document.getElementById('down');const messageInput = document.getElementById('message-input');const sendButton = document.getElementById('send');const upButton = document.getElementById('up');let isInputHidden = false;function createDanmuElement(text) {const danmu = document.createElement('div')danmu.textContent = text;danmu.style.position = 'absolute'//弹幕进入danmu.style.left = '-200px'//弹幕高度随机danmu.style.top = Math.floor(Math.random() * (danmuContainer.clientHeight - 30)) + 'px'//颜色随机danmu.style.color = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`//大小随机danmu.style.fontSize = Math.floor(Math.random() * 20) + 12 + 'px'//弹幕不换行danmu.style.whiteSpace = 'nowrap'//添加在后面danmuContainer.appendChild(danmu)return danmu}function moveDanmu(danmu) {//弹幕初始位置let left = -200 const speed = Math.floor(Math.random() * 3 ) + 1//从左到右const Timer = setInterval(() => {//实现右移,每次移动一个speedleft += speeddanmu.style.left = left + 'px'if (left > danmuContainer.clientWidth) {clearInterval(Timer)//关闭定时器后要移除弹幕danmuContainer.removeChild(danmu)}}, 10)}//传值,把打字框里的文本传给弹幕sendButton.addEventListener('click', function() {const text = messageInput.valueconst danmu1 = createDanmuElement(text)moveDanmu(danmu1)messageInput.value = ''});upButton.addEventListener('click', function() {isInputHidden =!isInputHiddenif (isInputHidden) {Down.classList.add('hidden')upButton.textContent = '弹出'} else {Down.classList.remove('hidden')upButton.textContent = '收起'}})//先飘一些弹幕for (let i = 0; i < 5; i++) {const text = `弹幕1111`const danmu = createDanmuElement(text)moveDanmu(danmu)}</script>
</body>
</html>
视频:
滚动弹幕