繁体   English   中英

字体大小更改时保持div的比率

[英]Keep ratio of a div when the font size changes

我有一个固定宽度和高度的div,字体大小为16px,如下所示

<div id="mydiv" style="font-size:16px;height:40px;line-height:40px;width:160px;background:orange;text-align:center;">
  hello world
</div>

我有一个允许更改字体大小的输入文本

<input type="text" id="input">

<button> change size </button>

JS:

$('button').on('click', function(){

  var value = $('#input').val();

  $('#mydiv').css('font-size', value + 'px');

});

例如,如果输入30的大小,则文本将超出div,我想要实现的是保持该比例,因此当字体大小更改时,我希望div更改尺寸以保持长宽比。 我该怎么做?

https://jsfiddle.net/mody5/x6t2dn3e/1/

更改其font-size时,您需要重新计算div widthheightline-height 仅通过更新其font-size ,就不会改变其他任何内容。

$('button').on('click', function() {
  var div = $('#mydiv');

  // These methods return the value unit-less, so they'll be integers
  // if defined.
  var currentWidth = div.width();
  var currentHeight = div.height();

  // Parsing the values to make sure you got integers.
  var currentFontSize = parseInt(div.css('font-size'), 10);
  var currentLineHeight = parseInt(div.css('line-height'), 10);
  var value = parseInt($('#input').val(), 10);

  var newFontSize = value + 'px';

  // Here we keep the ratio between width and height, considering
  // the current and new font-size.
  var newWidth = ((currentWidth * value) / currentFontSize) + 'px';
  var newHeight = ((currentHeight * value) / currentFontSize) + 'px';
  var newLineHeight = ((currentLineHeight * value) / currentFontSize) + 'px';

  // Applying all the styles at once.
  div.css({
    fontSize: newFontSize,
    width: newWidth,
    height: newHeight,
    lineHeight: newLineHeight
  });
});

演示版

为什么不只使用em值? 这正是它的用途:相对于字体大小应用值…

 .test { font-size:16px; height:2.5em; line-height:2.5em; width:10em; background:orange; text-align:center; } 
 <div class="test"> hello world </div> 

尝试更改字体大小,您会看到所有div都在增长。 使用此网站可帮助您计算良好的em值: http : //pxtoem.com/

(这是您的更新jsfiddle: https ://jsfiddle.net/x6t2dn3e/9/)

您可以在样式中结合使用内嵌块和填充。

像这样:

display:inline-block;padding:15px

在这里查看更新的小提琴: https : //jsfiddle.net/donal/p3hrctsf/2/

 $('button').on('click', function(){ var value = $('#input').val(); $('#mydiv').css('font-size', value + 'px'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mydiv" style="display: inline-block; font-size:16px;padding: 15px;background:orange;text-align:center;"> hello world </div> <br> <input type="text" id="input"> <button>Change Font Size</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM