使用伪元素生成爱心
不多bb直接上代码
.love {
position: fixed;
width: 20px;
height: 20px;
background-color: red;
transform: rotate(45deg);
opacity: 0;
animation: love 1s ease;
}
.love::after {
position: absolute;
display: block;
content: "";
width: 20px;
height: 20px;
border-radius: 50%;
transform: translate(0px, -10px);
background-color: inherit;
}
.love::before {
position: absolute;
display: block;
content: "";
width: 20px;
height: 20px;
border-radius: 50%;
background-color: inherit;
transform: translate(-10px, 0px);
}
<div class='love'></love>
我们可以通过使用伪元素结合之前说过的定位和css3的transform属性来生成爱心
那么我们想点击页面让爱心随着鼠标移动并且随机颜色的爱心,且当鼠标点击后爱心往上移动并逐渐失效
先申明一个函数 生成十六进制的颜色
function getColor() {
let newStr = ''
let str = '1234567890ABCDEF'
for (let i = 0; i < 6; i++) {
newStr += str.charAt(Math.floor(Math.random() * 16))
}
return '#' + newStr
}
console.log(getColor());
然后动画属性
@keyframes love {
0% {
transform: rotate(45deg) translateY(0);
opacity: 1;
}
100% {
transform: rotate(45deg) translateY(-15px);
opacity: 0;
}
}
现在需要的效果是鼠标点击页面,页面生成爱心,爱心的颜色是随机的。并且爱心有动画效果
思路:
1 点击页面生成div
2 给div加上love属性 让它前后有伪元素生成爱心
3 获取鼠标的位置赋值给div的left top
4 将生成的div放到body中
5 给div赋值不同颜色
6 一段时间让dom消失
附上完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
@keyframes love {
0% {
transform: rotate(45deg) translateY(0);
opacity: 1;
}
100% {
transform: rotate(45deg) translateY(-15px);
opacity: 0;
}
}
html,
body {
height: 100%;
width: 100%;
}
* {
margin: 0;
padding: 0;
}
.love {
position: fixed;
width: 20px;
height: 20px;
background-color: red;
transform: rotate(45deg);
opacity: 0;
animation: love 1s ease;
}
.love::after {
position: absolute;
display: block;
content: "";
width: 20px;
height: 20px;
border-radius: 50%;
transform: translate(0px, -10px);
background-color: inherit;
}
.love::before {
position: absolute;
display: block;
content: "";
width: 20px;
height: 20px;
border-radius: 50%;
background-color: inherit;
transform: translate(-10px, 0px);
}
</style>
</head>
<body>
<!-- <div class="love"></div> -->
</body>
<script>
// 编写一个函数,获得一个十六进制的随机颜色的字符串(例如:#20CD4F)
function getColor() {
let newStr = ''
let str = '1234567890ABCDEF'
for (let i = 0; i < 6; i++) {
newStr += str.charAt(Math.floor(Math.random() * 16))
}
return '#' + newStr
}
console.log(getColor());
// 给页面绑定点击事件
document.querySelector('body').onclick = function(e) {
let div = document.createElement('div')
div.className = 'love'
//获取鼠标位置 xy 位置
let x = e.clientX
let y = e.clientY
div.style.left = 5 + x + 'px'
div.style.top = -30 + y + 'px'
document.body.append(div);
div.style.background = getColor()
setTimeout(() => {
div.remove()
}, 500)
}
</script>
</html>
上面的代码可以直接运行