缩放文本以适应带过渡的浏览器大小

问题描述 投票:0回答:1

我有一些文本,我想在悬停按钮时将其调整为浏览器的 100%。如何使此文本适合浏览器/容器?

我知道用字体大小,你可以做像

font-size:100vw
这样的事情,但是字体大小的动画是抖动的,所以我不能使用这个方法。 '

http://jsfiddle.net/0n15mfyL/

对于那些想知道抖动的人来说,当字体缩小时会很明显:http://jsfiddle.net/rbk48upd/

javascript css transform
1个回答
0
投票

我在考虑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>

© www.soinside.com 2019 - 2024. All rights reserved.