首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript缩放文本以适应固定分区

JavaScript缩放文本以适应固定分区
EN

Stack Overflow用户
提问于 2010-11-12 22:54:15
回答 19查看 85.8K关注 0票数 57

在JavaScript/jQuery中,如何在固定宽度的Div中缩放可变长度的文本行,以使一行始终适合Div (作为一行)?

谢谢。

EN

回答 19

Stack Overflow用户

回答已采纳

发布于 2010-11-12 23:14:50

这在某种程度上是一种攻击,但可以做你想做的事情。

<div id="hidden-resizer" style="visibility: hidden"></div>

将它放在页面的底部,这样它就不会移动页面上的其他元素。

然后执行以下操作:

var size;
var desired_width = 50;
var resizer = $("#hidden-resizer");

resizer.html("This is the text I want to resize.");

while(resizer.width() > desired_width) {
  size = parseInt(resizer.css("font-size"), 10);
  resizer.css("font-size", size - 1);
}

$("#target-location").css("font-size", size).html(resizer.html());
票数 71
EN

Stack Overflow用户

发布于 2012-05-16 06:01:14

我已经写了一个jQuery插件来做这件事:

http://michikono.github.com/boxfit

该插件将水平和垂直缩放文本到框内的最大可用尺寸,然后将其居中。

您唯一需要做的就是定义一个包含文本的div:

<div id="scale">some text</div>

然后打电话给:

$('#scale').boxfit()

该方法将接受一些参数来禁用/启用文本换行和居中对齐。

票数 14
EN

Stack Overflow用户

发布于 2013-11-29 17:20:53

对于新的浏览器,您可以使用Inline-SVG。这可以通过CSS像图像一样缩放。好了!

.smallerVersion{
max-width: 50%
}
<!DOCTYPE html>
<html>
<head>
<title>Scale SVG example</title>
</head>

<body>





<h2>Default version:</h2>
<svg viewBox="0 0 240 80" xmlns="http://www.w3.org/2000/svg">
  <style>
    .small { font: italic 13px sans-serif; }
    .heavy { font: bold 30px sans-serif; }

    /* Note that the color of the text is set with the    *
     * fill property, the color property is for HTML only */
    .Rrrrr { font: italic 40px serif; fill: red; }
  </style>

  <text x="20" y="35" class="small">My</text>
  <text x="40" y="35" class="heavy">cat</text>
  <text x="55" y="55" class="small">is</text>
  <text x="65" y="55" class="Rrrrr">Grumpy!</text>
</svg>

<h2>Scaled version:</h2>
<svg class="smallerVersion" viewBox="0 0 240 80" xmlns="http://www.w3.org/2000/svg">
  <style>
    .small { font: italic 13px sans-serif; }
    .heavy { font: bold 30px sans-serif; }

    /* Note that the color of the text is set with the    *
     * fill property, the color property is for HTML only */
    .Rrrrr { font: italic 40px serif; fill: red; }
  </style>

  <text x="20" y="35" class="small">My</text>
  <text x="40" y="35" class="heavy">cat</text>
  <text x="55" y="55" class="small">is</text>
  <text x="65" y="55" class="Rrrrr">Grumpy!</text>
</svg>




</body>

</html>

(width: 100%;)

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4165836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档