日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

元素宽度固定,根据字符串长度,计算fontSize,缩小字号适配页面

發布時間:2024/3/24 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 元素宽度固定,根据字符串长度,计算fontSize,缩小字号适配页面 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>動態獲取fontSize</title>

<style type="text/css">

? ? .box {

? ? ? ? width: 70px;

? ? ? ? background: #222222;

? ? ? ? overflow: hidden;

? ? ? ? white-space: nowrap;

? ? ? ? text-overflow: ellipsis;

? ? ? ? color: #ffffff;

? ? ? ? font-size: 100px;

? ? }

</style>

</head>

<script>

window.onload = function() {

? ? let box = document.getElementById('box')

? ? function getFontSize(str = '666,666.66', targetSize = 20) {

? ? ? ? let boxWith = box.offsetWidth;

? ? ? ? let fontSize = targetSize;

? ? ? ? let theCanvas = null;

? ? ? ? let practicalWidth = getWidth(str, fontSize)

? ? ? ? function getWidth(text, size) { // 使用canvas計算字符串展示所需寬度

? ? ? ? ? ? let font = `normal ${size}px Microsoft YaHei`

? ? ? ? ? ? const canvas = theCanvas || (theCanvas = document.createElement('canvas'));

? ? ? ? ? ? const context = canvas.getContext('2d');

? ? ? ? ? ? context.font = font;

? ? ? ? ? ? return Math.floor(context.measureText(text).width)

? ? ? ? }

? ? ? ? while ((10 <= fontSize) && (practicalWidth > boxWith)) { // 所需寬度小于實際寬度,或者計算字體大于最小字體10

? ? ? ? ? ? fontSize -= 2

? ? ? ? ? ? practicalWidth = getWidth(str, fontSize); // 重新計算目標字符串所需寬度

? ? ? ? ? ? boxWith = box.offsetWidth - getWidth('...', fontSize); // 文本溢出剔除...所占距離

? ? ? ? ? ? if (practicalWidth< boxWith) {

? ? ? ? ? ? ? ? break

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return fontSize; // 輸出fontSize

? ? }

? ? box.style.fontSize = `${getFontSize()}px`

}

</script>

<body>

? ? <div id="box" class="box">666,666.66</div>

</body>

</html>

總結

以上是生活随笔為你收集整理的元素宽度固定,根据字符串长度,计算fontSize,缩小字号适配页面的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。