jquery - 子元素字体大小根据父元素的高度动态调整

标签 jquery html css

我正在尝试以下代码,但它不起作用。从逻辑上讲应该没问题,但是谁能告诉我我在这里缺少什么?目标是 (h1) 标签的字体大小应根据其父标签的高度自动调整。

Code Pen Link

HTML

<div class="product-title">
  <h1>Some Title which should not cross parent height and adjust font-size dynamically</h1>
</div>

CSS

.product-title{
     height: 200px;
     width: 200px;
 }

JS

    function adjustFontSize() {
        $('#h1').each(function() {
        var child = $(this);
        var parent = child.parent();

        child.css('font-size', '18'); //set max default font size
        while (child.height() > parent.height() && parseInt(child.css('font-size')) > 9) { //check div height condition
              child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px"); //decrease font size accordingly
        }
       });
      }

最佳答案

好的,到此为止。这应该是你要找的。让我知道它是否不适合你!

$(window).load(function() {
  function adjustFontSize() {

    $('.product-title h1').each(function() {

      var child = $(this);
      var parent = child.parent();
      var fontSize = 3;
      child.css("font-size", fontSize + "em");
      while (child.height() > parent.height() && fontSize > .75) { //check div height condition
        fontSize -= .05;
        child.css('font-size', fontSize + "em"); //decrease font size accordingly
      }

    });

  }
  adjustFontSize();
});

关于jquery - 子元素字体大小根据父元素的高度动态调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223359/

相关文章:

JQuery 获取 div 中所有输入的值

php - 使用同一数据表中的 ajax 填充下拉列表

javascript - 使整个网页着色

javascript - 在 Chrome 的 Javascript 中更改占位符颜色

javascript - 使用 jquery 的 CodeIgniter 动态输入并插入到数据库

Javascript 仅在放置在 HTML 下方时才起作用

javascript - 水平对齐拇指

html - 获取底部边框而不在 css 中提供底部属性发生了什么我无法理解

html - 如何平滑地将 CSS 动画恢复到当前状态?

css - Fontawesome 无法通过 css 中的引用编号加载图标