提问者:小点点

Javascript:字体大小增加/减少移动文本


我有HTML页面,其中我正在使用javascript语法“document.body.style.fontsize=100/50/20”更改字体大小

当我尝试更改字体大小时,HTML会根据字体的增加/减少上下移动文本,用户无法保持更改字体大小之前的相同文本。

我怎样才能让用户留在原来的地方?


共2个答案

匿名用户

如果您希望您的用户切换字体大小的更改,那么这里需要JavaScript

document.body.style.fontsize只在一个方向上工作,可以应用该size但不能将其恢复到原始大小。

null

var font_is_large = false ;
function change_font_size( )
{
  demo_paragraph = document.getElementById( 'demo' );
  if (!font_is_large) {
  // size you want on button click //
    demo_paragraph.style.fontSize = "150%" ; 
    font_is_large = true ;
  }
  else {
   // initial font size on page load //
    demo_paragraph.style.fontSize = "100%" ;
    font_is_large = false ;
  }
}
<button type="button" onclick="change_font_size();">Change font size</button>

<p id="demo">lorem ipsum </p>

匿名用户

我从你的问题中了解到的是--你希望卷轴在改变字体大小之前所在的同一区域。

我希望这能奏效。

        //get scroll position in percentage
        var maxScroll = document.documentElement.scrollHeight;
        var pos = window.scrollY;
        var percent = Math.round((pos/maxScroll)*100) ;
        
        //change font size
        document.body.style.fontSize = '15px';

        //adjust scroll to be in the same area
        var newScrollHeight = document.documentElement.scrollHeight;
        var newClientScroll = (newScrollHeight * percent)/100;
        window.scrollY = newClientScroll;