本文用到了事件中的onclick事件和一些css属性
<script>
window.onload = function(){
document.onclick=function loveHeart(a){//添加点击事件
var div0 = document.createElement("div");//创建爱心的最外层父元素
var heartList = ["heartLeft","heartRight"];//创建爱心需要的两个div名称的数组
div0.style.left = a.clientX-45+"px";//获取当前点击的页面位置的横坐标
div0.style.top = a.clientY-45+"px";//获取当前点击的页面位置的纵坐标
div0.style.position = "absolute";
Object.assign(div0.style,{//设置父元素的样式
width:"90px",
height:"90px"
});
createHeart(div0);
document.body.appendChild(div0);//将div0放在body中
//创建爱心所需要的两个div以及设置其样式
function createHeart(parent){
for(var i = 0;i<heartList.length;i++){//for循环创建两个div以及为其设置样式
var div = document.createElement("div");
Object.assign(div.style,{
width:"50px",
height:"75px",
backgroundColor: "red",
borderTopLeftRadius:"50% 25px",//为左侧div设置左上角的圆角边框以及偏移距离
borderTopRightRadius:"50% 25px",//为左侧div设置右上角的圆角边框以及偏移距离
position:"absolute",
left:i === 0 ? "11px" : "29px",//利用三目运算符可以有效的简化代码
top: "0px",
transform:i === 0 ? "rotate(-45deg)" : "rotate(45deg)"//将两个子div旋转
});
parent.appendChild(div);//将两个子div放到父div中
}
}
}
}
</script>