vue動態設置style屬性修改背景圖片

原始class屬性設置背景樣式


  .bannerP {
    position: absolute;
    top: 0;
    left: 2.96rem;
    right: 0;
    bottom: 0;
    background: url(../../assets/img/backgroundp.jpg) no-repeat center;   //  本地靜態圖片路徑
    background-size: cover;
  }

通過JavaScript實現動態修改背景圖片

首先html中設置style爲 動態綁定 即 :style

 <div :class=" $store.state.isMobile?'bannerH':'bannerP'" ref="backGroundRef" :style="bacImage">
    </div>

在JavaScript方法中則可以通過修改綁定bacImage實現動態更換背景屬性。 

 mounted () {
            let imageName = 'mobile' //手機終端
            //  通過瀏覽器判斷終端爲手機(true) 或者 pc(false) 動態切換背景圖片
            if (!this.$store.state.isMobile) {
                imageName = 'web'  // pc 瀏覽器
                this.bacImage = {backgroundImage: 'url("https://rdet-oss-test.oss-cn-hangzhou.aliyuncs.com/admin/static/image/loginBackground.gif")'}
            }
            else {
                this.bacImage = {backgroundImage: 'url("https://rdet-oss-test.oss-cn-hangzhou.aliyuncs.com/admin/static/image/web_background.jpg")'}
            }

        },

 

發佈了56 篇原創文章 · 獲贊 12 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章