I have some text that I want to resize to 100% of the browser when hovering over a button. How can I make this text fit in the browser/container?
I know that using font size
you can do something like font-size:100vw
but the animation of font-size is very unstable so I can't use this method.
http://jsfiddle.net/0n15mfyL/
For those wondering about jitter, it's noticeable when the font is scaled down: http://jsfiddle.net/rbk48upd/
P粉7295188062023-09-09 09:58:14
I am considering requestAnimationFrame()
const hoverMe = document.querySelector('#hover-me') , animTextSizing = document.querySelector('#anim-text-sizing') , txtSizeStart = parseInt(window.getComputedStyle(animTextSizing).getPropertyValue('font-size')) ; let sizeLimit = 0, currentTxtSize = txtSizeStart ; hoverMe.onmouseover =_=> { sizeLimit = document.body.clientWidth; animGrow(); } hoverMe.onmouseout =_=> { sizeLimit = txtSizeStart; currentTxtSize++ animReduce(); } function animGrow() { animTextSizing.style['font-size'] = `${++currentTxtSize}px`; if ( animTextSizing.clientWidth < sizeLimit) requestAnimationFrame(animGrow); } function animReduce() { animTextSizing.style['font-size'] = `${--currentTxtSize}px`; if ( currentTxtSize > sizeLimit) requestAnimationFrame(animReduce); }
* { margin : 0; padding : 0; } #anim-text-sizing { font-size : 30px; width : fit-content; white-space : nowrap; background : #aabfe5; } #hover-me { position : fixed; background : red; color : white; top : 50%; left : 50%; padding : .5rem; cursor : zoom-in; }
<div id="hover-me">Hover me</div> <div id="anim-text-sizing"> Welcome to this Page </div>