HLJ 发布于
2022-09-02 19:01:05

js动态创建删除点赞小红心的实例代码

<!DOCTYPE html>
<html>
<head>
<title>点赞小红心</title>
<style type="text/css">
  div{background: rgb(209, 0, 0);
    width: 16px;
    height: 16px;
    border-radius: 20px;
    position: relative;
    margin: auto

  }
  img{margin-left: 2px;margin-bottom: 3px;}
</style>
</head>

<body style="padding:200px">
<div>
<div id="heart">
  <img src="http://www.good1230.com/dist/server/images/article/1662115890.png" onclick="myFunction()">
</div>

</div>
<script type="text/javascript">
function myFunction(){
  draw()
}
function draw(){
    const x1 = 0;
    const y1 = 0;
    const r = 60;
    const count = 5;
    const fixed = false;

    for (let i = 0; i < count; i++) {
      const keyName =Math.floor(Math.random()*1000)
 
      const radius = r + Math.floor(Math.random() * r / 2);
      const radian = Math.random() * Math.PI * 2;
      const x2 = radius * Math.sin(radian) + x1;
      const y2 = radius * Math.cos(radian) + y1;

  const keyframes = `
    @keyframes floatheart${keyName} {
        0% {
          opacity: 0;
        }
        1% {
          opacity: 0;
          transform: translate(${x1}px,${y1}px);
        }
        2% {
          opacity: 1;
          transform: translate(${x1}px,${y1}px);
        }
        80% {
          opacity: 1;
          transform: translate(${x2}px,${y2}px);
        }
        100% {
          opacity: 0;
          transform: translate(${x2}px,${y2}px);
        }
   }`

  const style = document.createElement('style');
        style.type = 'text/css';
        style.id = `heart_id_${keyName}`
        style.innerHTML = keyframes;
        document.getElementsByTagName('head')[0].appendChild(style);

  const styles = {
    container:`
      opacity: 0;
      position: absolute;
      height: 18px;
      width: 18px;
      border-radius: 50%;
      background: #d10000 url("http://www.good1230.com/dist/server/images/article/1662115890.png") center center no-repeat;
      background-size: 10px;
      display: block;
      top:0px;
      animation: floatheart${keyName} 3s ease-out;
   `,
  };

  const heart_box = document.getElementById('heart')
  // 创建标签
  let element = document.createElement('div')

      element.id = `heart_${keyName}`
      element.style.cssText = styles.container
  
       heart_box.appendChild(element)

  // 移除标签
  setTimeout(function(){
    const heart_element = document.getElementById(`heart_${keyName}`)
    heart_box.removeChild(heart_element)

    const heart_style = document.getElementById(`heart_id_${keyName}`)
    document.head.removeChild(heart_style)
  }, 3000)

}
}

</script>

</body>
</html>
当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2022-09-02/592.html
最后生成于 2023-06-27 21:38:23
此内容有帮助 ?
0