<!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>
.container {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 150px;
}
.item {
position: absolute;
box-sizing: border-box;
width: 170px;
height: 170px;
padding: 15px;
border-radius: 5px;
cursor: move;
background-color: lightblue;
}
.close {
position: absolute;
font-style: normal;
right: 5px;
top: 5px;
cursor: pointer;
}
.text {
font-size: 1.2em;
padding: 0 10px;
width: 250px;
height: 40px;
bottom: 40px;
position: fixed;
left: 0;
right: 0;
margin: auto;
border-radius: 5px;
border: 1px solid #aaa;
outline: none;
}
</style>
</head>
<body>
<div class="container" id="container">
</div>
<input type="text" id="txtWish" placeholder="许个愿吧" class="text">
<script src="./script/Untitled-1.js"></script>
</body>
</html>
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
let container = document.getElementById('container');
let nextZIndex = 1;
function createWish(content) {
let itemDiv = document.createElement('div');
itemDiv.className = 'item';
let textDiv = document.createElement('div');
textDiv.className = 'item-text';
textDiv.innerText = content;
let closeI = document.createElement('i');
closeI.className = 'close';
closeI.innerText = 'X';
container.appendChild(itemDiv);
itemDiv.appendChild(textDiv);
itemDiv.appendChild(closeI);
let r = getRandom(150, 256);
let g = getRandom(150, 256);
let b = getRandom(150, 256);
itemDiv.style.backgroundColor = `rgb(${r},${g},${b})`;
let maxTop = container.clientHeight - 170;
itemDiv.style.top = `${getRandom(0, maxTop)}px`;
let maxLeft = container.clientWidth - 170;
itemDiv.style.left = `${getRandom(0, maxLeft)}px`;
closeI.addEventListener('click', () => {
itemDiv.remove();
})
itemDiv.onmousedown = function (e) {
itemDiv.style.zIndex = nextZIndex;
nextZIndex++;
var x1 = e.clientX,
y1 = e.clientY;
var a1 = parseFloat(itemDiv.style.left),
b1 = parseFloat(itemDiv.style.top);
window.onmousemove = function (e) {
var x2 = e.clientX,
y2 = e.clientY;
var xDis = x2 - x1;
var yDis = y2 - y1;
var a2 = a1 + xDis;
var b2 = b1 + yDis;
if (a2 < 0) {
a2 = 0;
} else if (a2 > maxLeft) {
a2 = maxLeft;
}
if (b2 < 0) {
b2 = 0;
} else if (b2 > maxTop) {
b2 = maxTop;
}
itemDiv.style.left = a2 + "px";
itemDiv.style.top = b2 + "px";
};
window.onmouseup = function () {
window.onmousemove = null;
};
};
}
var txtWish = document.getElementById("txtWish");
txtWish.onkeydown = function (e) {
if (e.key !== "Enter") {
return;
}
if (!txtWish.value) {
return;
}
createWish(txtWish.value);
txtWish.value = "";
};
