简介:本文讲解如何使用html+css+js实现代码在网页中弹射出来的功能。
代码会不断的在屏幕上弹出然后消失
下面是完整的代码和详细的解释。
<!DOCTYPE html>
<html>
<head>
<title>Code Effect</title>
<style>
/* 设置#code元素的样式 */
#code {
position: fixed; /* 元素固定在视口中 */
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: transparent; /* 背景色透明 */
overflow: hidden; /* 溢出隐藏 */
color: rgb(0, 63, 150); /* 字体颜色 */
font-size: 110px; /* 字体大小 */
font-family: 'Courier New', monospace; /* 字体类型 */
}
</style>
</head>
<body>
<div id="code"></div>
<script>
/* 生成随机字符串并返回 */
function getRandomString() {
const stringList = [
"#include<iostream>\nusing namespace std;\n\nint main()\n{\n\tcout << \"Hello, World!\" << endl;\n\treturn 0;\n}",
"import math\n\nprint(math.sqrt(2))",
"for i in range(10):\n print(i)",
"public class HelloWorld {\n public static void main(String[] args) {\n System.out.println(\"Hello, World!\");\n }\n}",
"console.log(\"Hello, World!\");",
"def hello():\n print(\"Hello, World!\")\nhello()",
"var s = \"Hello, World!\";\nconsole.log(s);",
"using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello, World!\");\n }\n}"
];
return stringList[Math.floor(Math.random() * stringList.length)];
}
/* 创建代码块元素 */
function createCodeElement() {
const element = document.createElement("pre"); /* 用<pre>标签创建元素 */
element.innerHTML = getRandomString(); /* 将随机字符串作为元素内容 */
element.style.position = "absolute"; /* 元素的定位方式设为绝对定位 */
element.style.top = Math.random() * 100 + "%"; /* 随机设置元素的上边距 */
element.style.left = Math.random() * 100 + "%"; /* 随机设置元素的左边距 */
element.style.transform = "translate(-50%, -50%)"; /* 将元素居中显示 */
element.style.animation = "floatup 10s ease-out forwards"; /* 设置元素的动画效果 */
document.getElementById("code").appendChild(element); /* 将元素添加到#code中 */
setTimeout(() => {
element.remove(); /* 在5秒后删除元素 */
}, 5000);
}
setInterval(createCodeElement, 200); /* 每隔200毫秒调用createCodeElement函数来添加代码块 */
</script>
</body>
</html>