JQuery:动态图像调整大小

问题描述:

我正在尝试为wordpress做一个响应主题。为了准备,我使用JQuery创建了我的resize脚本,以便在需要时动态调整它。JQuery:动态图像调整大小

<html> 
<head> 
<script type="text/javascript" src="jquery.js" ></script> 
<? 
class generate_image { 

    var $image; 

    function __construct($getimage) { 
     $this->image = $getimage; 
    } 

    function display() { 
     $wrapper = '<img id="sample" src="' . $this->image . '">'; 
     return $wrapper; 
    } 


} 
$view = new generate_image("sample.jpg"); 
?> 

<script language="javascript" type="text/javascript"> 
    var resize = { 
    bindimage: function (containerid) { 
      var width = $(containerid).width(); 
      var height = $(containerid).height(); 

      var maxwidth = 1291; 
      $(window).resize(function(){ 

       var percent = $(window).width()/maxwidth; 
       var now_height = height * percent; 
       var now_width = width * percent; 

       $('img').attr('height', now_height); 
       $('img').attr('width', now_width); 

       $('.win_height').text("Windows Height: " + $(window).height()); 
       $('.win_width').text("Windows Width: " + $(window).width()); 

       $('.img_height').text("Image Height: " + $('img').height()); 
       $('.img_width').text("Image Width: " + $('img').width()); 

       $('.win_calcu').text("Image Width: " + now_height); 
      });//end of resize 
     }//end of bind function 

    }//end of object 

    $(document).ready(function(){ 
     resize.bindimage('img'); 
    }); 
    </script>* 
    </head> 
    <body> 
    <div> 

    <div class="image"> 
    <? echo $view->display(); ?> 
    </div> 
    <div class="information"> 
    <table> 
    <tr> 
    <td> 
    <p class="img_height">Image Height</p> 
    </td> 
    <td> 
    <p class="img_width">Image Width </p> 
    </td> 
    </tr> 
    <tr> 
    <td> 
    <p class="win_height">Window Height</p> 
    </td> 
    <td> 
    <p class="win_width">Window Width</p> 
    </td> 
    </tr> 
    <tr> 
    <td> 
    <p class="win_calcu"></p> 
    </td> 
    </tr> 
    </table> 
    </div> 

    </div> 
    </body> 
    </html> 

有什么想法?这适用于IE9,但不适用于Chrome,一旦我调整它的大小,它将高度和宽度设置为0。

尝试在now_height设置一个整数,now_width变量

var now_height = parseInt(height * percent); 
var now_width = parseInt(width * percent); 

也尝试调用$你的函数(窗口).load()事件

$(window).load(function(){ 
    resize.bindimage('img'); 
}); 

也签可变宽度的范围,你在调整大小功能中使用它的高度,但它在那里是不可读的......将你的代码改成这样的东西

<script language="javascript" type="text/javascript"> 
var width = 0; 
var height = 0; 
var resize = { 
bindimage: function (containerid) { 
     width = $(containerid).width(); 
     height = $(containerid).height(); 
+0

它有效。但它在屏幕分辨率时不缩小。 – 2012-01-05 10:00:05

+0

我发现了另一个问题,我希望它现在可以工作 – alex 2012-01-06 07:08:35

+0

您的意思是,if函数B嵌套在函数A中。函数A中的变量在函数B中不可读? – 2012-01-10 08:44:09