使用JQuery在window resize事件上调整css body font-size

时间:2011-05-11 15:32:16

标签: jquery css

我的页面布局完全基于em,以保持灵活性。正文字体大小设置为100%,允许在更改默认字体大小时调整所有内部元素的大小。另外我希望font-size适应窗口大小。假设窗口大20%会导致正文字体大小为120%。但无论我在哪里放置脚本或jQuery文件,脚本都不会被调用。

当前版本:

<?xml version="1.0" encoding="UTF-8"?>
<!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" xml:lang="en" lang="en">
  <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

    <title></title>

    <script src="jquery-1.5.2.js"></script>

    <style type="text/css">


body {font-size:100%; font-family:Verdana, Geneva, sans-serif; background:#FFC; margin:auto; left:center; text-align:center; vertical-align:top; width:100%;  height:100%; }

.....all the divs.....
    </style>
</head>
<body>
....content....

<script>
 $(window).one("load resize",function(){
    var dfheight = 768;     //size on which the original layout is based
    var dfwidth = 1024;      
    var winheight = $(window).height();
    var winwidth = $(window).width();
    var minheight = 600;      //i set min and max values//
    var minwidth = 800;
    var maxheight = 1050;
    var maxwidth = 1400;
    var heightfactor = (1/defheight)*winheight;     //the % factor by which the default height varies from the current window height//
    var widthfactor= (1/defwidth)*winheight;
    var difwidth = abs(winwidth-defwidth);
    var difheight = abs(winheight-defheight);
    var newfonthf = (100*heightfactor) + "%";
    var newfontwf = (100*widthfactor) + "%";
    if ((difheight>difwidth)&&(winheight<maxheight && winheight>minheight)){
        $('body').css("font-size",newfonthf);
    }
    else if ((difheight<=difwidth) && (winwidth<maxwidth && winwidth>minwidth)){
        $("body").css("font-size",newfontwf);
    }
    else if ((difheight>=difwidth && winheight>maxheight) || (difheight<=difwidth && winwidth>=maxwidth)){
        $("body").css("font-size","137%");
    }
    else if ((difheight>=difwidth && winheight<minheight) || (difheight<=difwidth && winwidth<=minwidth)){
        $("body").css("font-size","78%");
       }
     else { $("body").css("font-size","100%");
       } 
 }
 );
 </script>

</body>
</html>

2 个答案:

答案 0 :(得分:3)

这可能是因为您需要在该功能有效之前创建文档。尝试

$(document).ready( function() {
     $(window).one("load resize",function(){
     // rest of your code ...
     })
});

答案 1 :(得分:0)

有时不放入属性将无法正常工作

<script src="jquery-1.5.2.js"></script> 

应该是

<script src="jquery-1.5.2.js" type="text/javascript"></script> 

<script>  $(window).one("load resize",function(){ 

应该是

<script type="text/javascript"> 
$(document).ready(function(){
 $(window).one("load resize",function(){ 
...//stuff ommited
});//at the end