Rendering the sprite map through a loop in vue

describe

Render the sprite to the corresponding position through the loop statement.

train of thought

First calculate the width of a picture, and then calculate the distance between each picture. Adding these two distances is the position of the next picture. Here I have realized the effect of modifying another sprite picture when the mouse slides in. Move the mouse out and display back to the original picture.
HTML code

<template>
  <div class="content">
    <div class="box" v-for="(i,index) in 6" :key="index" @mouseover.prevent="over(index)" @mouseout.prevent="out(index)" >
      <span  alt="" class="icon_img" ></span>
      <div class="icon_name0">{
   
   {name}}</div>
    </div>
  </div>
</template>

js code

 methods:{
    getfor(){
      var spans = document.getElementsByTagName('span')
      //核心代码
      for (var i = 0; i < spans.length; i++) {
        var index = i * 32.2;
        spans[i].style.backgroundPosition = "0 -" + index + "px";

      }
    },
    over(id){//鼠标移入时的操作
      var spans = document.getElementsByTagName('span')
      var index = id * 32.2;
      spans[id].style.backgroundPosition = "-" + 34 + 'px' + " -" + index + "px";

    },
    out(id){//鼠标移出时的操作
      var spans = document.getElementsByTagName('span')
      var indey = id * 32.2;
      spans[id].style.backgroundPosition = "0 -" + indey + "px";
    }

  },
   mounted(){
    this.getfor()
  }

css style

.content{
  display: flex;
}
.box{
  width: 90px;
  height: 90px;
  background: #f5f5f5;
  text-align: center;
  padding-top: 10px;
  box-sizing: border-box;
  border-radius: 4px;
  margin-right: 10px;
  .icon_img{
    display: inline-block;
    width: 34px;
    height: 34px;
    background: url(../assets/main_category.png) 0 0 no-repeat;
  }
  .icon_name{
    color: #333;
    margin-top: 6px;
    font-size: 12px;
  }
}
.box:hover{
  background:#1DC6BC;
   color: #ffff;
   box-shadow: 2px 4px 5px rgb(11, 156, 148);
}
.box:hover .icon_name{
  color: #ffff;
}

Referenced article: https://blog.csdn.net/qq_41670147/article/details/103191670

Guess you like

Origin blog.csdn.net/i96249264_bo/article/details/122964052