如何自动更改div内的文本大小?

发布于 2024-11-09 07:18:50 字数 78 浏览 0 评论 0原文

我有一个带有 div 的背景图像。我想写一些文本,但是这个文本应该通过div改变字体大小。

I have a background image with a div. I want to write some text, but this text should change the font size through the div.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

匿名。 2024-11-16 07:18:50

我这样理解你的问题,你想将一些文本放入具有固定尺寸的给定 div 中,如果 div 太小而无法显示所有文本,则应缩小字体大小,直到文本适合 div 。如果这就是重点,这就是我的解决方案。

下面是一个 jQuery 实现的示例: http://jsfiddle.net/MYSVL/2/

这里 div

<div id="fitin">
    <div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div>

是一个具有固定大小的

#fitin {
    width: 300px;
    height: 100px;
    border: 1px solid black;
    overflow: hidden;
    font-size: 1em;
}

这个 JavaScript 可以完成这项工作。

$(function() {
    while( $('#fitin div').height() > $('#fitin').height() ) {
        $('#fitin div').css('font-size', (parseInt($('#fitin div').css('font-size')) - 1) + "px" );
    }
});

I understand your question this way, you would like to fit some text into a given div with a fixed dimension, and if the div is too small to show all the text, the font size should be shrinked until the text fits into the div. If that's the point, here is my solution.

Here is an example with a jQuery implementaion: http://jsfiddle.net/MYSVL/2/

Here is a div

<div id="fitin">
    <div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div>

With a fixed size

#fitin {
    width: 300px;
    height: 100px;
    border: 1px solid black;
    overflow: hidden;
    font-size: 1em;
}

This JavaScript will do the job.

$(function() {
    while( $('#fitin div').height() > $('#fitin').height() ) {
        $('#fitin div').css('font-size', (parseInt($('#fitin div').css('font-size')) - 1) + "px" );
    }
});
殤城〤 2024-11-16 07:18:50

FlowType.js 将会做到这一点:调整字体大小以匹配边界元素,无论是 div 还是其他元素类型。

实现 FlowType 的示例:

  1. 设置您的样式

    <前><代码>正文{
    字体大小:18px;
    行高:26px;
    }

  2. 从 GitHub 下载 FlowType 并将其引用包含在你的头部元素

    flowtype.jQuery.js
    
  3. Call流类型

    $('body').flowtype();
    
  4. (可选)更新默认设置

    $('body').flowtype({
    最低:500,
    最大:1200,
    最小字体:12,
    最大字体:40,
    字体比例:30,
    线比:1.45
    });
    

查看他们的主页以获取交互式演示

FlowType.js will do just that: resize the font to match the bounding element, be it a div or another element type.

An example of implementing FlowType:

  1. Set up your style

    body {
    font-size: 18px;
    line-height: 26px;
    }
    
  2. Download FlowType from GitHub and include a reference to it in your head element

    flowtype.jQuery.js
    
  3. Call FlowType

    $('body').flowtype();
    
  4. (optional) Update default settings

    $('body').flowtype({
    minimum   : 500,
    maximum   : 1200,
    minFont   : 12,
    maxFont   : 40,
    fontRatio : 30,
    lineRatio : 1.45
    });
    

Check out their homepage for an interactive demo

ぶ宁プ宁ぶ 2024-11-16 07:18:50

我不完全确定我理解你的问题,但我认为你要问的是如何将文本放入预定义大小的特定容器中。我将尝试回答这个问题。

客户端

当您想在客户端按需执行此操作时,您必须运行 Javascript。这个想法是:

  1. 生成一个不可见的div并将其样式设置为:

    位置:绝对;
    顶部:0;
    左:0;
    宽度:自动;
    高度:自动;
    显示:块;
    可见性:隐藏;
    font-family: /* 根据你原来的 DIV */
    font-size: /* 根据你原来的 DIV */
    空白: /* 根据您的原始 DIV */
    
  2. 将文本复制到其中

  3. 检查DIV的宽度是否超​​出原始 DIV 的大小。

  4. 调整font-size值不是简单地增加/减少,而是通过计算不可见和原始DIV之间的宽度差异。这将更快地偏离正确的大小。

  5. 转到步骤3

服务器端

没有可靠的方法在服务器上设置字体大小,以使其适合客户端渲染的容器。不幸的是,您只能根据预先测试的经验数据来估算大小。

I'm not completely sure I understand your question but I think what you're asking is how to fit text in a particular container of predefined size. I'll try to answer this question.

Client side

When you want to do this on demand on the client you will have to run Javascript. The idea is to:

  1. generate an invisible div and set its style to:

    position: absolute;
    top: 0;
    left: 0;
    width: auto;
    height: auto;
    display: block;
    visibility: hidden;
    font-family: /* as per your original DIV */
    font-size: /* as per your original DIV */
    white-space: /* as per your original DIV */
    
  2. copy your text to it

  3. check whether DIV's width exceeded the size of your original DIV.

  4. adjust font-size value by not simply incrementing/decrementing but rather by calculating width difference between your invisible and original DIV. This will deviate to correct size much faster.

  5. go to step 3.

Server side

There is no reliable way of setting font size on the server so it will fit your client rendered container. Unfortunately you can only approximate sizes on pretested empirical data.

一腔孤↑勇 2024-11-16 07:18:50

这个问题已经回答很久了,但我想添加一些注释。

从那时起,一个额外的 jQuery 插件被添加到宇宙中: FlowType.js

https://github.com/simplefocus /FlowType.JS

我尝试了给定的解决方案和插件(包括 FlowType.JS),最后我编写了自己的解决方案和插件。我只是想将其作为“灵感”包含在这里。我使用不同的方法:我计算文本大小大于其父级的比率。我不知道这是否有意义,但对我来说效果很好。

    /* shrinkText jQuery Plugin  */

(function( $ ){

  $.fn.shrinkText = function() {

    var $_me = this;
    var $_parent = $_me.parent();

    var int_my_width = $_me.width();
    var int_parent_width = $_parent.width();

    if ( int_my_width > int_parent_width ){

      rl_ratio =   int_parent_width / int_my_width;

      var int_my_fontSize = $_me.css("font-size").replace(/[^-\d\.]/g, '');

      int_my_fontSize = Math.floor(int_my_fontSize * rl_ratio);

      $_me.css("font-size", int_my_fontSize + "px");

    }
  };

})( jQuery );

它假设块级元素中有一个内联元素,它通过重新计算字体大小来缩小内联元素。

HTML:

<h1 style="white-space:nowrap;">
  <a href="#" >Macrobenthos of the North Sea - Miscellaneous worms</a>
</h1>

JavaScript:

if( jQuery().shrinkText ){
    $("#title a").shrinkText();
}

The question has been answered since long, but I'd like to add some notes.

Since, an extra jQuery plugin has been added to the universe: FlowType.js

https://github.com/simplefocus/FlowType.JS

I tried my hand at the given solutions and plugins (including FlowType.JS), in the end I wrote my own. I just like to include it here as 'inspiration'. I use a different approach: I calculate the ratio that the size of the text is larger then it's parent. I don't know if it makes sense, but for me it works nicely.

    /* shrinkText jQuery Plugin  */

(function( $ ){

  $.fn.shrinkText = function() {

    var $_me = this;
    var $_parent = $_me.parent();

    var int_my_width = $_me.width();
    var int_parent_width = $_parent.width();

    if ( int_my_width > int_parent_width ){

      rl_ratio =   int_parent_width / int_my_width;

      var int_my_fontSize = $_me.css("font-size").replace(/[^-\d\.]/g, '');

      int_my_fontSize = Math.floor(int_my_fontSize * rl_ratio);

      $_me.css("font-size", int_my_fontSize + "px");

    }
  };

})( jQuery );

It assumes a inline-element within a block-level element, it shrinks the inline element by recalculating the font-size.

HTML:

<h1 style="white-space:nowrap;">
  <a href="#" >Macrobenthos of the North Sea - Miscellaneous worms</a>
</h1>

JavaScript:

if( jQuery().shrinkText ){
    $("#title a").shrinkText();
}
日暮斜阳 2024-11-16 07:18:50

您必须预加载图像才能获取图像的宽度和高度。

一旦获得尺寸,您就可以“尝试”不同的字体大小:

$("<img/>").appendTo(document.body).attr('src','myBackground.png').load(function(){
    var width = $(this).width(), height = $(this).height(),
        $div = $("#myDivId"),
        font = 30;

    do{
      font--;
      $div.css('font-size',font);
    }while($div.width()>width || $div.height()>height || font == 0);

    $div.width(width);
    $div.height(height);
});

You have to preload the image to get the width and height of the image.

As soon as you got the dimensions you can "try" different fontsizes:

$("<img/>").appendTo(document.body).attr('src','myBackground.png').load(function(){
    var width = $(this).width(), height = $(this).height(),
        $div = $("#myDivId"),
        font = 30;

    do{
      font--;
      $div.css('font-size',font);
    }while($div.width()>width || $div.height()>height || font == 0);

    $div.width(width);
    $div.height(height);
});
独行侠 2024-11-16 07:18:50

这是一个带有 JQuery 和 HTML5 数据注释的全局函数,用于定义块大小,请看一下:

不要问我为什么需要表格:-),宽度函数在 Jquery 1.7 上最适合表格... Divs 无宽度

用法:

<table>
 <tr>
    <td class="caa" data-text-max-width="500" data-text-max-height="80">
       The Text is Here
    </td>
 </tr>
</table>

添加功能:

$(function () {
    var textConsts = {
        MIN_SIZE_OF_A_TEXT: 9
    };

    $('*[data-text-max-width]').each(function () {

        var textMaxWidth = $(this).data("text-max-width");
        var textMaxHeight = $(this).data("text-max-height");
        var minSizeOfaText = $(this).data("text-min-size");

        $(this).css('font-size', '9em');

        if (minSizeOfaText == null || !($(this).hasData("text-min-size")))
            minSizeOfaText = textConsts.MIN_SIZE_OF_A_TEXT;

        if (textMaxWidth == null || !($(this).hasData("text-max-width")))
            textMaxWidth = $(this).parent().width();

        if (textMaxHeight == null || !($(this).hasData("text-max-height")))
            textMaxHeight = $(this).parent().height();

        var curentWidth = $(this).width();
        var curentFontSize = 0;
        var numberOfRounds = 0;
        var currentHeigth = $(this).height();
        curentFontSize = parseInt($(this).css('font-size'));
        var lineHeigth = parseInt($(this).css('line-height'));
        if (currentHeigth > (curentFontSize * lineHeigth)) {
            curentWidth += curentFontSize * lineHeigth;
        }

        while (curentWidth > textMaxWidth || currentHeigth > textMaxHeight) {

            curentFontSize = parseInt($(this).css('font-size'));
            curentFontSize -= 1;

            $(this).css('font-size', curentFontSize + "px");

            curentWidth = $(this).width();
            currentHeigth = $(this).height();

            if (currentHeigth > (curentFontSize * 1.5))
                curentWidth += curentFontSize * 1.5;

            numberOfRounds += 1;

            if (numberOfRounds > 1000)
                break;

            if (curentFontSize <= minSizeOfaText)
                break;
        }

        $(this).css('height', textMaxHeight + "px");
        $(this).css('width', textMaxWidth + "px");
    });

});

Here is a global function with JQuery and HTML5 Data annotations to define the block size take a look:

Don't ask me why I need the table :-) , the width function works best with tables... on Jquery 1.7 .. Getting no width for Divs

Usage :

<table>
 <tr>
    <td class="caa" data-text-max-width="500" data-text-max-height="80">
       The Text is Here
    </td>
 </tr>
</table>

Function to add:

$(function () {
    var textConsts = {
        MIN_SIZE_OF_A_TEXT: 9
    };

    $('*[data-text-max-width]').each(function () {

        var textMaxWidth = $(this).data("text-max-width");
        var textMaxHeight = $(this).data("text-max-height");
        var minSizeOfaText = $(this).data("text-min-size");

        $(this).css('font-size', '9em');

        if (minSizeOfaText == null || !($(this).hasData("text-min-size")))
            minSizeOfaText = textConsts.MIN_SIZE_OF_A_TEXT;

        if (textMaxWidth == null || !($(this).hasData("text-max-width")))
            textMaxWidth = $(this).parent().width();

        if (textMaxHeight == null || !($(this).hasData("text-max-height")))
            textMaxHeight = $(this).parent().height();

        var curentWidth = $(this).width();
        var curentFontSize = 0;
        var numberOfRounds = 0;
        var currentHeigth = $(this).height();
        curentFontSize = parseInt($(this).css('font-size'));
        var lineHeigth = parseInt($(this).css('line-height'));
        if (currentHeigth > (curentFontSize * lineHeigth)) {
            curentWidth += curentFontSize * lineHeigth;
        }

        while (curentWidth > textMaxWidth || currentHeigth > textMaxHeight) {

            curentFontSize = parseInt($(this).css('font-size'));
            curentFontSize -= 1;

            $(this).css('font-size', curentFontSize + "px");

            curentWidth = $(this).width();
            currentHeigth = $(this).height();

            if (currentHeigth > (curentFontSize * 1.5))
                curentWidth += curentFontSize * 1.5;

            numberOfRounds += 1;

            if (numberOfRounds > 1000)
                break;

            if (curentFontSize <= minSizeOfaText)
                break;
        }

        $(this).css('height', textMaxHeight + "px");
        $(this).css('width', textMaxWidth + "px");
    });

});
萌辣 2024-11-16 07:18:50

当你在 div 中有一个复杂的 HTML 并且你想保持不同元素之间的比例时,我扩展了 DanielB 解决方案:

$(function() {
    $(window).on('resize', function() {
        $('#fitin').css('font-size', '1em');
        var count = 0;
        while( count< 30 && $('#fitin').height() > $('#fitin div').height() ) { 
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) + 1) + "px");
            });
            count++;
        } 
        count = 0;
        while( count< 30 && $('#fitin div').height() > $('#fitin').height()-20 ) {
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) - 1) + "px");
            })
            count++;
        }
    });
    $(window).trigger('resize');  
});

I extend DanielB solution in the case when you have a complex HTML inside the div and you want to maintains ratio between different elements:

$(function() {
    $(window).on('resize', function() {
        $('#fitin').css('font-size', '1em');
        var count = 0;
        while( count< 30 && $('#fitin').height() > $('#fitin div').height() ) { 
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) + 1) + "px");
            });
            count++;
        } 
        count = 0;
        while( count< 30 && $('#fitin div').height() > $('#fitin').height()-20 ) {
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) - 1) + "px");
            })
            count++;
        }
    });
    $(window).trigger('resize');  
});
情深缘浅 2024-11-16 07:18:50

我已经制作了更好版本的 @DanielB 代码,也许它可以节省某人的时间:)

(只需将 RESIZABLE 类添加到您想要更改的 div 中)

$(document).ready(function() {
    $(window).resize(function() {

        $('.RESIZABLE').each(function(i, obj) {
            $(this).css('font-size', '8em');

            while ($(this).width() > $(this).parent().width()) {
                $(this).css('font-size', (parseInt($(this).css('font-size')) - 1) + "px");
            }
        });






    });
});

I have made better version of @DanielB code, maybe it save someone time :)

(Just add class RESIZABLE to div you want to be changed)

$(document).ready(function() {
    $(window).resize(function() {

        $('.RESIZABLE').each(function(i, obj) {
            $(this).css('font-size', '8em');

            while ($(this).width() > $(this).parent().width()) {
                $(this).css('font-size', (parseInt($(this).css('font-size')) - 1) + "px");
            }
        });






    });
});
听你说爱我 2024-11-16 07:18:50

在这里查看这个示例 http://codepen.io/LukeXF/pen/yOQWNb,您可以在页面加载和页面调整大小上使用一个简单的函数来实现奇迹。

function resize() {  
    $('.resize').each(function(i, obj) {
        $(this).css('font-size', '8em');

        while ($(this).width() > $(this).parent().width()) {
            $(this).css('font-size', (parseInt($(this).css('font-size')) - 1) + "px");
        }
    });
}

Check out this example here http://codepen.io/LukeXF/pen/yOQWNb, you can use a simple function on page load and page resize to make the magic happen.

function resize() {  
    $('.resize').each(function(i, obj) {
        $(this).css('font-size', '8em');

        while ($(this).width() > $(this).parent().width()) {
            $(this).css('font-size', (parseInt($(this).css('font-size')) - 1) + "px");
        }
    });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文