<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>随机竖向句子动画</title> <style> /* 设置全屏容器样式 */ body, html { margin: 0; padding: 0; overflow: hidden; width: 100%; height: 100%; background-color: #f0f0f0; } /* 设置句子样式 */ .sentence { position: absolute; white-space: nowrap; font-size: 24px; writing-mode: vertical-rl; opacity: 0; /* 初始不透明度为0 */ transition: opacity 1s; /* 过渡效果 */ animation: moveRight linear infinite; pointer-events: none; } .sentence:nth-child(8){ color: #099b67; opacity: 1!important; } .sentence:last-of-type{ color: red; opacity: 1!important; } /* 定义动画效果 */ @keyframes moveRight { 0% { transform: translateX(-100vw); } 100% { transform: translateX(100vw); } } </style> </head> <body> <script> // 定义句子数组 const sentences = ['枯藤老树昏鸦','小桥流水人家','古道西风瘦马','夕阳西下','断肠人在天涯']; // 获取屏幕宽高 const screenWidth = window.innerWidth; const screenHeight = window.innerHeight; function generateRandomColor() { const letters = '0123456789ABCDEF'; let color = '#'; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } // 生成随机位置和不透明度的句子 function generateSentences() { const fragment = document.createDocumentFragment(); const gridSize = 90; // 每个网格的大小 const rows = Math.ceil(screenHeight / gridSize); const cols = Math.ceil(screenWidth / gridSize); const totalSentences = rows * cols; for (let i = 0; i < totalSentences; i++) { const sentenceElement = document.createElement('div'); sentenceElement.className = 'sentence'; sentenceElement.innerText = sentences[i % sentences.length]; const row = Math.floor(i / cols); const col = i % cols; // 计算句子在网格内的随机位置 const x = col * gridSize + Math.random() * (gridSize - 20); // 减去20是为了避免句子靠近网格边缘 const y = row * gridSize + Math.random() * (gridSize - 20); sentenceElement.style.left = <code>${x}px</code>; sentenceElement.style.top = <code>${y}px</code>; sentenceElement.style.opacity = Math.random().toFixed(2); sentenceElement.style.animationDuration = 20 + Math.random() * 10 + "s"; // sentenceElement.style.color = generateRandomColor(); fragment.appendChild(sentenceElement); } document.body.appendChild(fragment); } // 页面加载完毕后生成句子并启动动画 window.onload = () => { generateSentences(); } </script> </body> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » 文字整屏滚动 喜欢 (0)or分享 (0)