类font-size自适应实现方案jquery + svg版本 2022年4月7日15:30:21

目标

font-size自适应
在外框宽高发生变化时,文字自动缩放

效果图

设置字体30px,外框宽度25px高度50px,自动缩小到25的框内
在这里插入图片描述

源码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #aaa {
      font-size: 30px;
      color: blue;
      width: 50px;
      height: 25px;
      display: flex;
      border: 1px solid #000;
    }
  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(function () {
      function autoSizeSpan(parent, text, options = {}) {
        const img = `<img/>`;
        const $img = $(img);
        // 添加参数
        for (const key in options) {
          if (Object.hasOwnProperty.call(options, key)) {
            $img.prop(key, options[key])
          }
        }
        parent.append($img);
        const imgStyle = window.getComputedStyle($img[0], null);
        const svg = `<svg xmlns="http://www.w3.org/2000/svg" 
                          version="1.1" 
                          xml:space="preserve" 
                          stroke="${imgStyle.color}" 
                          width="${imgStyle.fontSize.slice(0, -2) * text.length}px" 
                          height="${imgStyle.lineHeight == 'normal' ? imgStyle.fontSize.slice(0, -2) * 1.5 : imgStyle.lineHeight}">
                            <g>
                              <text font-size="${imgStyle.fontSize}" 
                                    startOffset="50%" 
                                    x="50%" 
                                    y="50%" 
                                    text-anchor="middle" 
                                    dominant-baseline="middle">${text}</text>
                            </g>
                      </svg>`;
        console.log(svg);
        $img.attr('src', `data:image/svg+xml;utf8,${svg}`);
        const oldStyle = $img.attr('style');
        $img.attr('style', `object-fit:scale-down;width: 100%;height: 100%;${oldStyle ?? ''}`);
      }

      // 字符串转base64
      function encode(str) {
        // 对字符串进行编码
        var encode = encodeURI(str);
        // 对编码的字符串转化base64
        var base64 = btoa(encode);
        return base64;
      }

      autoSizeSpan($("#aaa"), '你好');
    });
  </script>
</head>

<body>
  <div id="aaa">
  </div>
</body>

</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值