固定宽度,字体大小自适应(超出宽度自动缩小)

核心:通过计算缩小的比例,用transform: scale()实现缩放字体

htm部分

用两个相同的盒子,一个用来计算宽度,从而计算缩放比例,另一个用来展示。

<template>
  <div class="combo-card">
    <div class="card-content">
     //展示
      <div ref="txt" class="card-left online" :style="cradLeftStyle">
        <span class="card-left-symbol">&yen;</span>
        <span class="card-left-amount">99999999999999</span>
        <span class="card-left-floor">.99999</span>
      </div>
        //计算宽度
      <div ref="block" class="card-left online block">
        <span class="card-left-symbol">&yen;</span>
        <span class="card-left-amount">99999999999999</span>
        <span class="card-left-amount">.99999</span>
      </div>
      <div class="card-right">
        <p>右边位置</p>
      </div>
    </div>
    <div style="margin-top:70px">==============5555================1010</div>
  </div>
</template>

js部分

需要安装插件:

完整代码:


<script>
import { ResizeObserver } from 'resize-observer'

export default {
  data () {
    return {
      cradLeftStyle: {}
    }
  },
  mounted () {
    const txtWidth = this.$refs.txt.getBoundingClientRect().width

    this.myObserver = new ResizeObserver((entries) => {
      const block = entries[0]
      const blockWidth = block.contentRect.width

      console.log('他们俩的宽度', block.contentRect.width, txtWidth)
      if (blockWidth > txtWidth) {
        this.cradLeftStyle = {
          transform: `scale(${txtWidth / blockWidth})`,
          'transform-origin': 'left'
        }
      }
    })

    this.myObserver.observe(this.$refs.block)
  },
  deactivated () {
    if (this.myObserver) {
      this.myObserver.disconnect()
    }
  }
}
</script>

css部分

用来计算宽度的盒子通过隐藏

需要固定自适应部分的宽度,和字体初始大小

完整样式代码:

<style lang="less" scoped>
.combo-card {
    text-align: left;
}
.block {
  position: absolute;
  opacity: 0;
  width: auto !important;
}
.card-content {
  font-family: PingFangSC-Regular, PingFang SC;
  position: absolute;
  top: 0;
  display: flex;
  align-items: center;
  background: #b9dae5;
  .card-left {
    width: 300px;
    color: #844700;
    &.online {
      white-space: nowrap;
    }
    .card-left-symbol {
      margin: 0 auto;
      font-size: 38px;
    }
    .card-left-amount {
      margin: 0 auto;
      font-size: 50px;
      font-weight: bold;
    }
    .card-left-floor {
      font-size: 42px;
      font-weight: bold;
    }
  }
  .card-right {
    background: red;
    margin-left: 28px;
    color: #844700;
  }
}
</style>

效果展示:

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值