首页 > 解决方案 > 在 CSS 中使用计算开关来定义 v-img 的 top 属性

问题描述

我想根据窗口的当前断点定义 v-img 的 top 属性。

我想这样定义它:

<v-img contain id="logo-transparent" :top="logoTop" :width="logoWidth" :src="logoTransparent" class="hidden-xs-only"></v-img>

计算出的属性如下所示:

logoTop(){
            switch (this.$vuetify.breakpoint.name) {
                case 'xl': return "-4%"
                case 'lg': return "-6%"
                case 'md': return "-8%"
                case 'sm': return "-8%"
                case 'xs': return 0
                default:
                    return "-4%"
            }
        },

和这样的CSS:

#logo-transparent{
  z-index: 1;
  width: 400px;
  height: 300px;
  position: absolute;
  right: -1%;
}

但问题是 v-img 没有 top 属性。

我想使用我的计算函数来定义图像的 CSS,如下所示:

logoTop(){
            return {
                "--top-property" : switch (this.$vuetify.breakpoint.name) {
                                    case 'xl': return 400
                                    case 'lg': return 300
                                    case 'md': return 300
                                    case 'sm': return 200
                                    case 'xs': return 0
                                    default:
                                        return 400
                                }
            }
            
        },

能够在css中像这样使用它:

top : var(--top-property)

但在这种情况下,我似乎不能使用开关。

我怎么能做到?

标签: cssvue.jsvuetify.js

解决方案


switch不返回任何东西。你应该使用这样的变量

logoTop() {
    let topProperty;
    switch (this.$vuetify.breakpoint.name) {
        case 'xl':
            topProperty =  400;
            break;
        case 'lg':
        case 'md':
            topProperty =  300;
            break;
        case 'sm':
            topProperty =  200;
            break;
        case 'xs':
            topProperty =  0;
            break;
        default:
            topProperty = 400;
    }
    return {
        "--top-property" : topProperty
    }
},


推荐阅读