目标
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>