【问题标题】:How to change height dynamically according to width with aspect ratio 4:3 in vue js?如何在vue js中根据宽高比4:3的宽度动态改变高度?
【发布时间】:2021-08-11 10:43:59
【问题描述】:

我想以 4:3 的纵横比根据宽度按比例改变高度。这里的宽度是 100vw。所以我在挂载的钩子中通过 this.$refs.imageDiv.clientWidth 得到了宽度像素。现在,当我在 console.log() 中记录宽度和高度数时,它会完美记录。但是当我尝试使用计算属性动态更改高度时,它不会改变预期的高度。什么问题?

<template>
 <div ref="imageDiv" :style="imageStyle" class="top-blog__photo">
   <img
        :src="require(`../assets/samplePics/${blog.photo}.jpg`)"
        alt="Blog Photo"
      />
  </div>
</template>

<script>
export default{
 props: ['blog'],
 data(){
  iWidth: 0,
  iHeight: 0,
 },
 computed: {
  imageStyle(){
   return{
    width: iWidth+"px",
    height: iHeight+"px",
   }
  }
 },
 mounted(){
  if(this.iWidth === 0){
   this.iWidth = this.$refs.imageDiv.clientWidth;
   this.iHeight = this.iWidth / (4/3);
  }
  window.addEventListener("resize", ()=>{
   this.iWidth = this.$refs.imageDiv.clientWidth;
   this.iHeight = this.iWidth / (4/3);
  })
 }
}
</script>

<style lang="scss" scoped>
.top-blog{
 &__photo{
  img{
   width: 100%;
   height:100%;
   object-fit: cover;
  }
 }
}
</style>

【问题讨论】:

    标签: javascript html css vue.js


    【解决方案1】:

    首先,你不应该使用=== 运算符进行赋值,只使用= 运算符,例如:

    mounted(){
      if(this.iWidth === 0){
       this.iWidth = this.$refs.imageDiv.clientWidth;
       this.iHeight = this.iWidth / (4/3);
      }
      window.addEventListener("resize", ()=>{
       this.iWidth = this.$refs.imageDiv.clientWidth;
       this.iHeight = this.iWidth / (4/3);
      })
     }
    

    其次,在computed 中使用this.iWidth + 'px' 代替iWidththis.iHeight + 'px' 代替iHeight,如下所示:

    computed: {
      imageStyle(){
       return{
        width: this.iWidth + 'px',
        height: this.iHeight + 'px',
       }
      }
     },
    

    【讨论】:

    • 我疯了。犯了很多错误
    • 您好,先生,我已经解决了这些问题,但还不行
    • 在计算中,您使用了width: iWidth+"px", height: iHeight+"px",,您必须使用this 来表示iWidthiHeight,如下所示:width: this.iWidth + 'px',height: this.iHeight + 'px',
    • 我错过的另一件事 ?
    【解决方案2】:

    如果您的应用要在足够现代的浏览器中使用,您可以使用aspect-ratio CSS 属性:

    .mydiv {
      width: 250px;
      aspect-ratio: 4 / 3;
      background-color: red;
    }
    <div class="mydiv">
    </div>

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 1970-01-01
      • 2022-08-19
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多