前端固定宽度,文本字体大小自适应

前端固定宽度,文本字体大小自适应

前言

闲来无事自己琢磨的,记录一下,仅供参考。

正文

新建AdaptiveText.js文件

export default class AdaptiveText {
  /**
   *
   * @param {string} selector 要展示自适应文本的dom,必填值
   * @param {number} [width] 固定宽度,为0时自动获取父级dom宽度,可选值
   * @param {object} [styles] 文本dom的styles
   * @param {string} styles.fontSize 字体大小,必传
   * @param {number} [minScale] 最小缩放倍率,默认0.6
   */
  constructor({selector = '', width = 0, minScale = 0.6, styles = {}}) {
    this.selector = selector
    this.styles = styles
    this.content = null
    this.width = width
    this.minScale = minScale
  }

  set text(v) {
    if (!this.content) {
      this.content = this._createContent()
    }

    this.content.innerText = v

    this._scaleText()
  }

  _createContent() {
    if (!this.selector) throw new Error('HTML selector is invalid')
    const span = document.createElement('span');
    Object.assign(span.style, this.styles)
    span.style.display = 'inline-block'
    document.querySelector(this.selector).appendChild(span)
    if (this.width === 0) {
      this.width = document.querySelector(this.selector).clientWidth
    }
    return span
  }

  _scaleText() {
    const widthInPixels = this.content.offsetWidth;
    if (widthInPixels > this.width) {
      let scale = this.width / widthInPixels;//缩放比例
      this.content.style.transformOrigin = ' left center'
      scale = scale > 1 ? 1 : scale
      scale = scale > this.minScale ? scale : this.minScale
      this.content.style.transform = `scale(${scale})`
    }
  }

}

使用说明

1.vue2、vue3中调用


<template>

  <input type="text" v-model="text" @input="onchange">
  <-- 目标文本区域 需要一个id和固定宽度-->
  <div style="width: 190px;height:28px;border: 1px solid #e0e0e0;white-space: nowrap;font-size: 16px;" ref="target"
       id="text"></div>

</template>

<script>
import {defineComponent} from 'vue'
// 导入文件
import AdaptiveText from "path/AdaptiveText";

export default defineComponent({
  name: 'IndexPage',
  data() {
    return {
      text: '广东省深圳市宝安区'
    }
  },
  mounted() {
  
  	// vue2或vue3都要要在mounted里面初始化,否则找不到dom会报错
    this.conte = new AdaptiveText({
      selector:'#text',
      styles:{
        fontSize:'16px'
      }
    })
	// 初始化赋值(选用)
    this.conte.text = this.text
  },
  methods: {
    onchange() {
    	// 文本赋值
      this.conte.text = this.text
    },
  },
})
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值