当前第2页 返回上一页
兼容性
IE浏览器以及一些旧版浏览器不支持CSS变量,因此,需要使用css-vars-ponyfill,是一个ponyfill,可在旧版和现代浏览器中为CSS自定义属性(也称为“ CSS变量”)提供客户端支持。由于要开启watch监听,所以还有安装MutationObserver.js。
安装:
1 | npm install css-vars-ponyfill mutationobserver-shim --save
|
然后,在themes.js文件中引入并使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import 'mutationobserver-shim'
import cssVars from 'css-vars-ponyfill'
cssVars({
watch: true
})
const createLink = (() => {
let $link = null
return () => {
if ($link) {
return $link
}
$link = document.createElement( 'link' )
$link.rel = 'stylesheet'
$link.type = 'text/css'
document.querySelector( 'head' ).appendChild($link)
return $link
}
})()
const toggleTheme = (theme = 'default' ) => {
const $link = createLink()
$link.href = `./themes/${theme}.css`
return theme
}
export default toggleTheme
|
开启watch后,在IE 11浏览器点击切换主题开关不起作用。因此,每次切换主题时都重新执行cssVars(),还是无法切换主题,原因是开启watch后重新执行cssVars()是无效的。最后,只能先关闭watch再重新开启。成功切换主题的themes.js代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import 'mutationobserver-shim'
import cssVars from 'css-vars-ponyfill'
const createLink = (() => {
let $link = null
return () => {
if ($link) {
return $link
}
$link = document.createElement( 'link' )
$link.rel = 'stylesheet'
$link.type = 'text/css'
document.querySelector( 'head' ).appendChild($link)
return $link
}
})()
const toggleTheme = (theme = 'default' ) => {
const $link = createLink()
$link.href = `./themes/${theme}.css`
cssVars({
watch: false
})
setTimeout( function () {
cssVars({
watch: true
})
}, 0)
return theme
}
export default toggleTheme
|
查看所有代码,请移步Github项目地址。
记住主题
实现记住主题这个功能,一是可以向服务器保存主题,一是使用本地存储主题。为了方便,这里主要使用本地存储主题的方式,即使用localStorage存储主题。具体实现请移步Github项目地址。
本文来自PHP中文网,CSS教程栏目,欢迎学习
以上就是Vue使用CSS变量实现切换主题功能的详细内容,更多文章请关注木庄网络博客!
返回前面的内容
相关阅读 >>
vue的elementui实现自定义主题
css变量 var()的用法是什么?css变量 var()的用法详解
bootstrap怎么更改主题
vue使用css变量实现切换主题功能
更多相关阅读请进入《css变量》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » Vue使用CSS变量实现切换主题功能