只用JavaScript面向对象改变透明度的运动

711 阅读1分钟

有一个有背景颜色的div,我们要改变其透明度,要求不能用html和css来实现,只用js该如何实现呢?

一,首先我们先看看用常规的html+css+js的代码

1.html代码:

<body>
 
  <div id="box">
 
  </div>
 
</body>

2.css代码:

<style type="text/css">
  * {
    margin: 0;
    padding: 0;
  }
 
  div {
    width: 100px;
    height: 100px;
    background: deepskyblue;
    position: absolute;
    left: 200px;
    top: 200px;
    opacity: 0.3;
  }
</style>

3.JavaScript代码:

<script type="text/javascript">
  var obj = document.querySelector("div");
 
  // 鼠标移入,颜色由浅到深
  obj.onmouseover = function () {
    start(100);
  }
 
  // 鼠标移出 颜色由深到浅
  obj.onmouseout = function () {
    start(30);
  }
  let alpha = 30; // 设置透明度临时值
  let times = '';
  function start(target) {
    // 设置步进值
    let speed = target - alpha > 0 ? 1 : -1;
    times = setInterval(() => {
      // 增加透明度临时值
      alpha += speed;
      // 临时值等于透明度,则清除定时器
      if (alpha == target) clearInterval(times);
      obj.style.opacity = alpha / 100;
    }, 30)
 
  }
</script> 

二,只用JavaScript实现的代码

<script>
        //创建节点
        function Box(ele, attr, style, father) {
            this.newEle = document.createElement(ele);
            this.attr = attr;
            this.style = style;
            this.father = father || document.body;
            this.setAttr();
        }
        //设置属性
        Box.prototype.setAttr = function () {
            //Object.assign方法用来将源对象(source)的所有可枚举属性,复制到目标对象(target)。它至少需要两个对象作为参数,第一个参数是目标对象,后面的参数都是源对象。
            Object.assign(this.newEle, this.attr);
            // 传递样式才调用
            this.style && this.setStyle();
            this.append();
        };
        // 设置style样式
        Box.prototype.setStyle = function () {
            Object.assign(this.newEle.style, this.style);
 
        }
        Box.prototype.append = function () {
            this.father.appendChild(this.newEle)
        }
 
        new Box('div', 
            {id: 'box'},
            {
            width: '200px',
            height: '200px',
            background: 'red',
            opacity: '0.3'
            });
        //获取节点
        var boxObj = document.getElementById('box');
        let alpha = 30;// 设置透明度临时值
        let times = '';
        function changeAlpha(target) {
            // 设置步进值
            let speed = target - alpha > 0 ? 1 : -1;
            //设置定时器
            times = setInterval(() => {
                // 增加透明度临时值
                alpha += speed;
                // 临时值等于透明度,则清除定时器
                if (alpha == target) clearInterval(times);
                boxObj.style.opacity = alpha / 100;
            }, 30)
 
        }
        // 鼠标移入,颜色由浅到深
        boxObj.onmouseover = function () {
            changeAlpha(100);
        }
 
        // 鼠标移出 颜色由深到浅
        boxObj.onmouseout = function () {
            changeAlpha(30);
        }
    </script>