繁体   English   中英

根据文本长度和窗口大小调整字体大小

[英]Adjust font size based on text length and window resize

我正在使用此代码根据元素标题中文本的长度来调整文本大小。 在用户调整浏览器的大小之前,此方法非常有用。 如果使用户的窗口变小,可以做些什么来调整文本大小。 比方说,如果窗口宽度小于600像素,则更改字体大小。

如何才能在页面加载时做到这一点,代码现在做了什么-而且还可以在调整浏览器大小时更改字体大小?

$(".title").css('font-size', function () { // get length of text for title and adjust font size
    var $numWords = $(this).text().length;
    if (($numWords >= 1) && ($numWords < 40)) {
        return "26px";
    }
    else if (($numWords >= 40) && ($numWords < 60)) {
        return "24px";
    }
    else if (($numWords >= 60) && ($numWords < 100)) {
        return "22px";
    }
    else if (($numWords >= 100)) {
        return "20px";
    }
});

您可以为此使用jQuery的resize()函数( http://api.jquery.com/resize/

$(document).ready(function() {
    onResize()
});

onResize = function() {
    if(window.width() < 600){
        // Do stuff
     }
}

$(window).bind('resize', onResize);

您可以像这样测量文本的实际渲染大小:

var text = $(this).text();
var tmp = $("<div/>").css({position: "absolute"}).text(text);
$("BODY").append(tmp);
var width = tmp.width();
tmp.remove();

如果您确定div的样式与页面上的样式相同(相同的字体,粗细,大小),则可以告诉您它的大小。 应该可以对此进行迭代以搜索适合可用空间的大小(具有合理的截止值)。 如果您在页面上有成百上千个这样的页面,速度会很慢,但是对于几个标题来说应该没问题。

<div id="cont" style="font-family: Verdana; background-color: #ccc;">
    <div id="textContent">fox jump over the lazy dog...fox jump over the lazy dog...fox jump over the lazy dog</div>
</div>  
<script>
    var textContainer = document.getElementById('cont');
    var text = document.getElementById('textContent');
    var textLength = text.innerText.length;
    var firstLoadWidth;

    if (textLength >= 1 && textLength < 40) {
        cont.style.fontSize = '26px';
    }
    else if (textLength >= 1 && textLength < 60) {
        cont.style.fontSize = '24px';
    }
    else if (textLength >= 1 && textLength < 100) {
        cont.style.fontSize = '22px';
    }
    else if (textLength > 100) {
        cont.style.fontSize = '20px';
    }

    window.addEventListener('load', function () {
        firstLoadWidth = window.innerWidth;
    });
    window.addEventListener('resize', function () {
        var getSize = window.innerWidth / firstLoadWidth;
        getSize <= 1 ? text.style.fontSize = getSize + 'em' : text.style.fontSize = '1em';
    }, false);
</script>

只需在字体大小中使用百分比

p {
font-size:200%;
}

该百分比是由于父标签“ div”的宽度引起的

暂无
暂无

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

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