【问题标题】:change the style of element dynamically using VUEJS使用 VUEJS 动态改变元素的样式
【发布时间】:2021-10-07 23:23:11
【问题描述】:

我有 div,我想使用 VueJS 应用程序动态更改其位置。 我在数据函数中有变量 x,我想将它分配给 top。 这是我写的代码,但它不起作用 在模板标签中:

<template>
    <div id="squar" v-if="showSquar" :style="{top: x}" @click="countClicks">
        click here
    </div>  
</template>

在样式标签中:

#squar{
    width: 100px;
    height: 100px;
    border-radius: 5px;
    background: rgb(0,70,40,0.8);
    color: white;
    text-align: center;
    vertical-align: middle;
    line-height: 100px; 
    position: absolute; 
    
    }

我工作的组件不是 App 组件

【问题讨论】:

  • :style="{top: x}" 更改为 :style="`top: ${x}`" 您可能还需要包含 !important

标签: javascript css vue.js


【解决方案1】:

这对我有用:

<template>
  <div id="squar" v-if="showSquar" :style="{ top: top + 'px' }">
    click here
  </div>
</template>

<script>
export default {
  data() {
    return {
      showSquar: true,
      top: 200
    };
  }
};
</script>
<style scoped>
#squar {
  width: 100px;
  height: 100px;
  border-radius: 5px;
  background: rgb(0, 70, 40, 0.8);
  color: white;
  text-align: center;
  vertical-align: middle;
  line-height: 100px;
  position: absolute;
}
</style>

【讨论】:

    【解决方案2】:

    现在你正在绑定一个style attribute,它不会像css那样做任何你需要写的事情

    <template>
        <div id="squar" v-if="showSquar" :style="`top:${x}`" @click="countClicks">
            click here
        </div>  
    </template>
    

    您可能还需要包含!important 标签。

    :style="`top:${x}!important`" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2018-01-04
      • 2019-03-15
      • 2013-11-01
      • 1970-01-01
      • 2012-11-14
      相关资源
      最近更新 更多