vue 切换div背景图片

切换背景图片:

1.定义数据列表及属性。

 /** 灯列表 */
 protected lamps: Array<any>= [{Name: "1号灯" , Open: false},{Name: "2号灯", Open: false}];
View Code

2.定义不同状态下的css样式。

.close
{
    width: 100%;
    height: 100%;
    background-image: url("close_light.png");
    background-size:50% 50% ;
    background-repeat:no-repeat ;
    background-position: 50% 30%;
}
.open
{
    width: 100%;
    height: 100%;
    background-image: url("open_light.png");
    background-size:50% 50% ;
    background-repeat:no-repeat ;
    background-position: 50% 30%;
}
View Code

 

3.对class进行绑定操作。

4.根据“Open”属性的值切换class的名称。

 <div :class="item.Open === false ? 'close' : 'open'" @click="click(item)">
      <div class="name">{{item.Name}}</div>
 </div>
View Code 

完整代码如下

<template>
    <div>
        <div> 
            <label>背景图片切换</label>
        </div>
        <div class="content">
            <div class="lamp" v-for="(item,index) in lamps" :key="index">
                <div :class="item.Open === false ? 'close' : 'open'" @click="click(item)">
                    <div class="name">{{item.Name}}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';
import Component from "vue-class-component"

/**
 * 更改div背景图片
 */
@Component({})
export default class ChangeBackgroundImage extends Vue {
  
  /** 灯列表 */
 protected lamps: Array<any>= [{Name: "1号灯" , Open: false},{Name: "2号灯", Open: false}];
  
  /**
   * 点击事件
   */
  protected click(item): void
  {
        item.Open = item.Open === false ? true : false;
        let message = (item.Open ? "开启" : "关闭") + item.Name;
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.content
{
    width: 100%;
    height:100%;

    float:left;
    margin-top:20px;
    
    position:relative;
    text-align: center;
    display: -webkit-flex; 
    align-items:center;
    justify-content:center;
}
.lamp
{
    height:100px;
    width: 100px;
    display: inline-block;
    margin-left:2%;
    margin-right:3%;
    margin-top:0.5%;
    opacity:0.9;
}
.close
{
    width: 100%;
    height: 100%;
    background-image: url("close_light.png");
    background-size:50% 50% ;
    background-repeat:no-repeat ;
    background-position: 50% 30%;
}
.open
{
    width: 100%;
    height: 100%;
    background-image: url("open_light.png");
    background-size:50% 50% ;
    background-repeat:no-repeat ;
    background-position: 50% 30%;
}

.close:hover,
.open:hover
{
    cursor: pointer;
}

.name
{
    font-size:12px;
    padding-top:100%
}
</style>

 

 

实现效果图:

 

   

 

 

   

 

   

 

posted @ 2020-03-13 15:37  不是少年也游荡  阅读(3583)  评论(0编辑  收藏  举报