我有一些文本,我想在悬停按钮时将其调整为浏览器的 100%。如何使此文本适合浏览器/容器?
我知道用字体大小,你可以做像
font-size:100vw
这样的事情,但是字体大小的动画是抖动的,所以我不能使用这个方法。 '
对于那些想知道抖动的人来说,当字体缩小时会很明显:http://jsfiddle.net/rbk48upd/
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>