我使用这段代码根据元素标题中文本的长度来调整文本大小。在用户调整浏览器的大小之前,这是非常有效的。如果用户的窗口变小,可以做什么来调整文本大小。例如,如果窗口宽度小于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";
}
});发布于 2014-06-01 19:57:03
<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>发布于 2014-06-01 19:11:06
为此,可以使用jQuery的resize()函数(http://api.jquery.com/resize/)
$(document).ready(function() {
onResize()
});
onResize = function() {
if(window.width() < 600){
// Do stuff
}
}
$(window).bind('resize', onResize);发布于 2014-06-01 19:15:35
您可以度量文本的实际呈现大小,如下所示:
var text = $(this).text();
var tmp = $("<div/>").css({position: "absolute"}).text(text);
$("BODY").append(tmp);
var width = tmp.width();
tmp.remove();如果您确保您的div样式将在页面上(相同的字体、重量、大小),那么这可以告诉您它有多大。应该可以迭代这个来搜索适合可用空间的大小(有一些合理的截止点)。这将是缓慢的,如果你有数百或数以千计的这些在一页,但对几个标题,应该是好的。
https://stackoverflow.com/questions/23983347
复制相似问题