2015年11月13日 星期五

CSS: 根據外框高度自動調整文字大小

參考來源是這篇文章,再加以改良。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
</head>

<body>
<style>
#div1{
    width:500px;
    height:500px;
    border:thin solid red;
}
</style>
<div id="div1">
    <div id="div2">test test</div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
resizeTxtH();
function resizeTxtH(){
    var wordboxX = $('#div1');
    var wordboxY = $('#div2');
    var wordboxX_h = $('#div1').height();
    var wordboxY_h = $('#div2').height();
    
    //初始化文字大小为最小
    wordboxY.css('font-size', '12px');
    
    var pxv = 0;
    
    for (var i = 12; i < 1000; i++) {
        if (wordboxY_h > wordboxX_h) {
            pxv = i - 2;
            wordboxY.css('font-size', pxv + 'px');
            alert('i = ' + i + ', pxv = ' + pxv + ', wordboxX_h = ' + wordboxX_h + ', wordboxY_h = ' + wordboxY_h);
            //结束循环
            break;
        }
        alert('i = ' + i + ', pxv = ' + pxv + ', wordboxX_h = ' + wordboxX_h + ', wordboxY_h = ' + wordboxY_h);
        wordboxY.css('font-size', i + 'px');
        wordboxY.css('border', 'thin solid blue');
        wordboxY_h = $('#div2').height();
    }
}
</script>
</body>
</html>

沒有留言:

張貼留言