最近在搞个人网站,想搞搞自定义背景图片
显然,直接将url写在css里面是修改不了的,自己实现动态修改CSS代码想想都觉得不可能
参考vue官方的对于style动态修改的篇章,可以发现有两种方法:
较为常用的是动态绑定类名,通过切换类名的方式进行css样式切换,虽然挺常用,但需要添加更换背景的时候还是要更改css文件
<script setup>
import {ref} from 'vue'
const bkg = ref("bkg1")
</script>
<template>
<div :class="bkg">
<button @click="bkg==='bkg1'?bkg='bkg2':bkg='bkg1'">change</button>
</div>
</template>
<style scoped>
.bkg1{
position: fixed;
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
background-image: url('https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.bkg2{
position: fixed;
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
background-image: url('https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
图片资源感谢大自然的馈赠(测试图片,视频 地址_测试图片地址-CSDN博客)
虽然是可以切换图片,但是根本没有实现自定义的功能
再看看vue官网,
现可以用内联样式绑定到vue,先试试
<script setup>
import {ref} from 'vue'
const bkg = ref("bkg1")
const url = ref("https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg")
</script>
<template>
<div :class="bkg" :style="{
'height': '100%',
'width': '100%',
'margin': '0px',
'padding': '0px',
'backgroundImage': 'url('+url+')',
'backgroundPosition': 'center',
'backgroundRepeat': 'no-repeat',
'backgroundSize': 'cover',
}">
<input type="text" v-model="url">
</div>
</template>
不过要注意的是需要把烤串写法改为小驼峰写法,
也就是像这样
background-image => backgroundImage
可以通过url更改图片了,功能实现了,但依然不够优雅
再看看文档
我只能说,你说的对,那确实是个好主意
<script setup>
import {ref, reactive} from 'vue'
const bkg = ref("bkg1")
const url = ref("https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg")
const bkgObj = reactive({
'height': '100%',
'width': '100%',
'margin': '0px',
'padding': '0px',
'backgroundImage': 'url('+url+')',
'backgroundPosition': 'center',
'backgroundRepeat': 'no-repeat',
'backgroundSize': 'cover',
})
</script>
<template>
<div :class="bkg" :style="bkgObj">
<input type="text" v-model="url">
</div>
</template>
代码确实更干净了
但还有优化空间
既然已经是js对象了,那么url也没有设置变量的必要了,再将可自定义的部分和不可自定义的分隔开,
<script setup>
import { onMounted, reactive } from "vue";
const basicBkgStyleObj = reactive({
position: "fixed",
height: "100%",
width: "100%",
display: "flex",
justifyontent: "center",
margin: "0px",
padding: "0px",
zIndex : "-1",
})
const customBkgStyleObj = reactive({
backgroundImage : "url('https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg')",
backgroundPosition : "center",
backgroundRepeat : "no-repeat",
backgroundColor : "hsla(0, 0%, 79%, 0.85)",
backgroundSize : "cover",
})
</script>
<template>
<div class="bkg" :style="[basicBkgStyleObj, customBkgStyleObj]">
<slot name="head"></slot>
<slot name="body"></slot>
</div>
</template>
最后再将customBkgStyleObj导出config.json文件
var file = JSON.stringify(customBkgStyleObj)
localStorage.setItem("bkgConfig", file)
后续读取小加一手,
完美