欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原生JS实现图片网格式渐显、渐隐效果

程序员文章站 2022-04-29 11:58:43
先给出效果图:   写的小组件支持图片的渐显、渐隐,并且可以是有序、随机两种方式。   我采用的原型是属性写在构造函数内,方法写在原型对象内。方法写构造函数内有个问...

先给出效果图:

原生JS实现图片网格式渐显、渐隐效果原生JS实现图片网格式渐显、渐隐效果

  写的小组件支持图片的渐显、渐隐,并且可以是有序、随机两种方式。

  我采用的原型是属性写在构造函数内,方法写在原型对象内。方法写构造函数内有个问题,就是每次调用这个方法就相当于重新实例化一次,举个粟子:

  实现网格效果的原理上是将读取图片的宽高,按照设定的参数,分成等高宽的网格(我用的span标签表示的网格),网格利用定位铺满整个图片,每个网格的背景图都是原图片,原理同sprite,利用background-position属性改变显示区域。接下来就是按照设定的顺序实现渐显或渐隐。渐显或渐隐用的是js的animation属性和css3的animation属性在属性值上有所区别,这次使用也才知道js的animation属性里有个animationfillmode(规定当动画不播放时(当动画完成时,或当动画有一个延迟未开始播放时),要应用到元素的样式。)属性值。

  我绑定的事件是点击,完全可以用其他事件或页面加载触发。我的代码稍加改动就可以实现网格式轮播图。

  下面给出源代码:

<!doctype html>
<head>
<title>网格效果</title>
<style>
  @charset "utf-8";
  /*css reset*/
  html{font-family:"helvetica neue",helvetica,stheiti,sans-serif;-webkit-text-size-adjust:100%;-moz-text-size-adjust:100%;-ms-text-size-adjust:100%;}
  body{-webkit-overflow-scrolling:touch;margin:0;}
  ul{margin:0;padding:0;list-style:none;outline:none;}
  dl,dd{margin:0;}
  a{display:inline-block;margin:0;padding:0;text-decoration:none;background:transparent;outline:none;color:#000;}
  a:link,a:visited,a:hover,a:active{text-decoration:none;color:currentcolor;}
  a,dt,dd{-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;}
  img{border:0;}
  p{margin:0;}
  input,button,select,textarea{margin:0;padding:0;border:0;outline:0;background-color:transparent;}
  /*css*/
  .origin-pic {
    display: inline-block;
    width: 200px;
    height: 200px;
  }
  .grid-area {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;
  }
  .grid {
    position: absolute;
  }
  #img1 {
    opacity: 1;
    width: 200px;
    height: 200px;
  }
  @keyframes fadeout{
    0% {opacity: 1}
    100% {opacity: 0}
  }
  @keyframes fadein{
    0% {opacity: 0}
    100% {opacity: 1}
  }
</style>
</head>
<body>
<div>
  <img class="origin-pic" src="./pic.jpg" />
</div>
<div id="grid_area" class="grid-area">
  <img id="img1" src="./pic.jpg" />
</div>
<script>
var gridsetting = {
  'cell': 10, // 行、列数量
  'mode': 'fadeout', // 备选参数: fadeout, fadein
  'sort': 'random', // 备选参数: inturn, random
  'num': 1, // 每次发生动作的网格数,目前只支持1
  complete: function() { // 事件完成时的回调函数
    console.log('ok!');
  }
};
var img1 = document.getelementbyid('img1');
(function(doc, setting, ele) {
  var defaults = {
    'speed': 20,
  };
  function grid(ele) {
    this.ele = ele;
    this.settings = object.assign({}, setting, defaults);
  }
  grid.prototype = {
    constructor: grid,
    // 构建ui
    _create: function() {
      var img = this.ele,
        settings = this.settings,
        cell = settings.cell,
        imgwidth = img.width,
        imgheight = img.height,
        gridwidth = imgwidth / cell, // 每个网格宽度
        gridheight = imgheight / cell, // 每个网格高度
        currenttop = 0,
        currentleft = 0,
        fragment = doc.createdocumentfragment(),
        i = 0,
        gridarr = [];
      img.style.display = 'none';
      for (; i < cell * cell; i++) {
        var spannode = doc.createelement('span');
        spannode.setattribute('id', i);
        spannode.style.csstext +=  'position: absolute;' +
                      'top: ' + currenttop + 'px;' +
                      'left: ' + currentleft + 'px;' +
                      'margin: 0;' +
                      'padding: 0;' +
                      'width: ' + gridwidth + 'px;' +
                      'height: ' + gridheight + 'px;' +
                      'opacity:' + settings.opacity + ';' +
                      'background: url('+ img.src + ');' +
                      'background-size: ' + imgwidth + 'px ' + imgheight + 'px;' +
                      'background-position: -' + currentleft + 'px -' + currenttop + 'px;';
        if (currentleft < (imgwidth - gridwidth)) {
          currentleft += gridwidth;
        } else {
          currentleft = 0;
          currenttop += gridheight;
        }
        fragment.append(spannode);
        gridarr.push(i);
      }
      this.gridarr = gridarr;
      doc.getelementbyid('grid_area').append(fragment);
    },
    // 渐显、渐隐
    _fade: function() {
      var gridarr = this.gridarr,
        clonearr = gridarr.slice(0),
        length = gridarr.length,
        settings = this.settings,
        sort = settings.sort,
        i = 0;
      switch(settings.mode) {
        case 'fadeout':
          if (sort == 'inturn') {
            // 按顺序渐隐
            var timer = setinterval(function() {
              doc.getelementbyid(gridarr[i]).style.animation = "fadeout 1s forwards";
              i++;
              if (i >= settings.cell * settings.cell) {
                clearinterval(timer);
                settings.complete();
              }
            }, settings.speed)
          } else if (sort == 'random') {
            // 随机渐隐
            var timer = setinterval(function() {
              i = clonearr.splice(math.random() * length--, 1);
              doc.getelementbyid(gridarr[i]).style.animation = "fadeout 1s forwards";
              if (length == 0) {
                clearinterval(timer);
                settings.complete();
              }
            }, settings.speed)
          }
          break;
        case 'fadein':
          if (sort == 'inturn') {
            // 按顺序渐渐显
            var timer = setinterval(function() {
              doc.getelementbyid(gridarr[i]).style.animation = "fadein 1s forwards";
              i++;
              if (i >= settings.cell * settings.cell) {
                clearinterval(timer);
                settings.complete();
              }
            }, settings.speed)
          } else if (sort == 'random') {
            // 随机渐显
            var timer = setinterval(function() {
              i = clonearr.splice(math.random() * length--, 1);
              doc.getelementbyid(gridarr[i]).style.animation = "fadein 1s forwards";
              if (length == 0) {
                clearinterval(timer);
                settings.complete();
              }
            }, settings.speed)
          }
          break;
        default:
          console.log('配置错误!');
      }
    },
    _checkmode: function() {
      if (this.settings.mode == 'fadein') {
        this.settings.opacity = 0;
      } else {
        this.settings.opacity = 1;
      }
    },
  };
  var gridarea = doc.getelementbyid('grid_area');
  gridarea.addeventlistener('click', function() {
    var event = new grid(ele);
    event._checkmode();
    event._create();
    event._fade();
  }, false);
})(document, gridsetting, img1);
</script>
</body>
</html>

以上所述是小编给大家介绍的原生js实现图片网格式渐显、渐隐效果,希望对大家有所帮助