原生js实现许愿墙
实现效果:
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./css/index.css">
</head>
<body>
<div class="container">
<!-- <div class="item">
世界和平
<span class="close">X</span>
</div> -->
</div>
<input type="text" class="txt" placeholder="许个愿望吧">
<script src="./js/index.js"></script>
</body>
</html>
CSS代码:
* {
padding: 0;
margin: 0;
}
html {
background-color: lightcyan;
width: 100%;
}
.txt {
position: absolute;
bottom: 30px;
width: 250px;
/* 水平居中 */
left: 0;
right: 0;
/* auto吸收剩余空间 */
margin: auto;
height: 30px;
border: 1px solid #ccc;
border-radius: 5px;
/* 首行缩进 */
text-indent: 1em;
font-size: 13px;
}
.item {
width: 170px;
height: 170px;
padding: 20px;
box-sizing: border-box;
/* border: 1px solid black; */
background: red;
border-radius: 5px;
border-bottom-right-radius: 80px 20px;
/* 盒子阴影 */
box-shadow: 0 0 5px 2px rgba(0, 0, 0, .2);
position: absolute;
left: 100px;
top: 80px;
/* 在文字处换行 */
word-wrap: break-word;
overflow: hidden;
}
.item .close {
position: absolute;
right: 5px;
top: 2px;
cursor: pointer;
}
javascrip代码:
var container = document.querySelector(".container");
var zindex = 1;
// 创建一个愿望
function creatWish(words) {
var div = document.createElement("div");
// 设置文字
div.innerHTML = words;
div.className = "item";
// 点击事件,让下层的盒子成为第一层的盒子
div.onclick = function() {
div.style.zIndex = zindex;
zindex++;
}
// 关闭按钮
var span = document.createElement("span");
span.className = "close";
span.innerHTML = "X";
div.appendChild(span);
// 颜色随机
div.style.background = `rgb(${getRandom(150,256)},${getRandom(150,256)},${getRandom(150,256)})`;
// 位置随机
var max_X = window.innerWidth - div.offsetWidth;
var max_Y = window.innerHeight - div.offsetWidth;
div.style.left = `${getRandom(0,max_X)}px`;
div.style.top = `${getRandom(0,max_Y)}px`;
// 关闭事件
span.onclick = function() {
container.removeChild(div);
}
container.appendChild(div);
}
//产生随机数
function getRandom(min, max) {
var dec = max - min;
return Math.floor(Math.random() * dec + min);
}
// 生成默认愿望
function init() {
var wishes = [
"高考加油",
"生日快乐",
"必胜"
]
for (let i = 0; i < wishes.length; i++) {
var wish = wishes[i];
creatWish(wish);
}
}
//文本框的回车事件
var txt = document.querySelector(".txt");
txt.onkeydown = function(e) {
if (e.keyCode !== 13) { //判断是否回车
return;
}
if (txt.value) {
creatWish(txt.value);
} else {
init();
}
}