js+css3实现随着文字不断增加,字体大小自动缩小,从而不超出范围并且不会裁切文字,有些场景可能有这个需要,点击查看效果。
下面是具体的代码:
<style type="text/css"> a { color: #333; text-decoration: none; } .wrapper { width: 80%; } .head { border: 1px solid red; margin: 1rem 0; text-align: center; font-size: 26px; overflow: hidden; } .head a { color: #20528f; font-weight: bold; font-family: Microsoft Yahei; white-space: nowrap; transition: font-size 100ms; } </style> <p>js实现文字增加,字体大小自动缩小不超出范围,请连续点击下面的追加文字,查看效果:</p> <div class="wrapper"> <h1 class="head"><a target="_blank" href="http://www.5imoban.net">我爱模板网 </a></h1> </div> <button onclick="addFont()">追加文字</button> <script type="text/javascript" src="https://www.sanqin.com/static/index/js/jquery1.42.min.js"></script> <script type="text/javascript"> const setFontSize = () => { const headWidth = $('.head').width() const headLinkWidth = $('.head a').width() let fontSize = 26 if(headLinkWidth > headWidth) { let flag = true do { const font = `normal ${fontSize}px arial` const canvas = document.createElement('canvas') const context = canvas.getContext('2d') context.font = font; const { width } = context.measureText($('.head a').text()) if(width <= headWidth) { flag = false } else { fontSize -- } } while(flag) } if(fontSize<5) { alert('不能再缩小了') } else { $('.head a').css('fontSize', fontSize + 'px') } } const addFont = () => { const text = $('.head a').text() $('.head a').text(text+text) setFontSize() } </script>