美文网首页
es6飘窗效果

es6飘窗效果

作者: 如此行走 | 来源:发表于2020-04-16 20:21 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>es6飘窗功能</title>
        <style type="text/css">
          * {
            margin: 0px;
            padding: 0px;
          }
    
          #ad {
            position: absolute;
            left: 0px;
            top: 0px;
            z-index: 1000;
          }
          #ad a.adclose {
            cursor: pointer;
            position: absolute;
            right: 0px;
            top: 0px;
            color: black;
            padding: 0 6px;
            background-color: #c7cfda;
          }
        </style>
      </head>
      <body>
        <div id="ad">
          <a class="adclose" onclick="hidead()">×</a>
          <a href="http://www.baidu.com" target="_blank"
            ><img src="time.jpg" width="150" height="150"
          /></a>
        </div>
        <script>
          class Flutter {
            constructor() {
              this.ad = document.querySelector('#ad')
              this.close = document.querySelector('.adclose')
              // 定义横纵坐标
              this.x = 0
              this.y = 0
              // 设置初始速度
              this.xv = 1
              this.yv = 1
              this.mytime = null
              this.init()
            }
            init() {
              // 定时器调用
              this.mytime = setInterval(() => {
                this.move()
              }, 40)
              // ad绑定鼠标悬停事件
              this.ad.onmouseover = () => {
                // 清除定时器
                clearInterval(this.mytime)
              }
              // 鼠标离开,重新触发定时器
              this.ad.onmouseout = () => {
                this.mytime = setInterval(() => {
                  this.move()
                }, 40)
              }
              this.close.onclick = () => {
                this.hidead()
              }
            }
            move() {
              if (this.x < 0 || this.x > window.innerWidth - this.ad.offsetWidth) {
                this.xv = -this.xv
              }
    
              if (
                this.y < 0 ||
                this.y > window.innerHeight - this.ad.offsetHeight - 1
              ) {
                this.yv = -this.yv
              }
              this.x += this.xv
              this.y += this.yv
              // 将xy坐标值赋予img css样式中的left与top
              this.ad.style.left = this.x + 'px'
              this.ad.style.top = this.y + 'px'
            }
            hidead() {
              document.body.removeChild(this.ad)
            }
          }
          new Flutter()
        </script>
      </body>
    </html>
    
    

    相关文章

      网友评论

          本文标题:es6飘窗效果

          本文链接:https://www.haomeiwen.com/subject/ojacmhtx.html