您的位置:首页 > 产品设计 > UI/UE

vue div backgroundSize 不起作用的解决办法

2018-02-27 00:00 120 查看
在使用绑定样式的功能时,发现对div的backgroundSize属性设置不起作用,于是只能 使用一个比较笨拙的办法,解决这个问题

初始加载是生效的,但是之后当点击按钮改变图片地址后,无法填充背景图片



改变背景之后



第一个使用的是计算属性,绑定style,使用background-size和backgSize都无效



下面的是使用原生js设置样式



第一个

<template>
<div>
<div class="img" :style="style"></div>
<button @click="prev">prev</button>
<button @click="next">next</button>
</div>
</template>

<script>
export default {
name: "swiper",
data() {
return {
cur_index: 0,
imgs: [
'https://i1.mifile.cn/a4/xmad_15195327867488_jlLnp.jpg',
'https://i1.mifile.cn/a4/xmad_15185161540821_qPMoX.jpg',
'https://i1.mifile.cn/a4/xmad_15193829171444_CQnuo.jpg',
'https://i1.mifile.cn/a4/xmad_15192945916761_ormJz.jpg',
],
}
},
computed: {
style() {
return {
background: `url('${this.imgs[this.cur_index]}') no-repeat`,
'backgroundSize': 'contain'
}
}
},
methods: {
prev() {
this.cur_index = (this.cur_index + this.imgs.length - 1) % this.imgs.length
},
next() {
this.cur_index = (this.cur_index + 1) % this.imgs.length
}
}
}
</script>

<style scoped>
.img {
width: 400px;
height: 300px;
border: 1px solid black;
}
</style>

第二个

<template>
<div>
<div class="img" :style="style" ref="swiper"></div>
<button @click="prev">prev</button>
<button @click="next">next</button>
</div>
</template>

<script>
export default {
name: "swiper",
data() {
return {
cur_index: 0,
imgs: [
'https://i1.mifile.cn/a4/xmad_15195327867488_jlLnp.jpg',
'https://i1.mifile.cn/a4/xmad_15185161540821_qPMoX.jpg',
'https://i1.mifile.cn/a4/xmad_15193829171444_CQnuo.jpg',
'https://i1.mifile.cn/a4/xmad_15192945916761_ormJz.jpg',
],
}
},
watch: {
cur_index() {
this.refresh()
}
},
methods: {
refresh() {
this.$refs.swiper.style.background = `url('${this.imgs[this.cur_index]}') no-repeat`
this.$refs.swiper.style.backgroundSize = 'contain'
},
prev() {
this.cur_index = (this.cur_index + this.imgs.length - 1) % this.imgs.length
},
next() {
this.cur_index = (this.cur_index + 1) % this.imgs.length
}
},
mounted() {
this.refresh()
}
}
</script>

<style scoped>
.img {
width: 400px;
height: 300px;
border: 1px solid black;
/*background-size: contain;*/
}
</style>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: