JQuery:动态图像调整大小

时间:2012-01-04 07:00:16

标签: jquery html image

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

<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。

1 个答案:

答案 0 :(得分:1)

尝试在now_height,now_width变量

上设置一个整数
var now_height = parseInt(height * percent);
var now_width = parseInt(width * percent);

也尝试在$(window).load()事件

上调用你的函数
$(window).load(function(){
    resize.bindimage('img');
});

还要检查你在resize函数中使用它的变量宽度,高度的范围,但它在那里是不可读的...将你的代码改为这样的

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