使用 JQuery / javascript 创建动态图像:我做错了什么?

2024-01-11

请看一下以下代码:(为了便于阅读,我删除了所有文档类型等)。

我想代码是非常不言自明的:JavaScript 代码从下图中检索高度和宽度,并创建两个新变量(newHeight 和 newWidth),它们缩小了原始值的 80%。当文档加载时,这两个新变量(newHeight 和 newWidth)应该分配给图像的高度和宽度属性,但这种情况不会发生。

有人可以帮我吗?

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript" />

<script type="text/javascript">
var width = $("#fluidimage").width();
var height = $("#fluidimage").height();

var imageresize = 80;
var newHeight = Math.round(height/100)*imageresize);
var newWidth = Math.round(width/100)*imageresize);
</script>

</head>
<body onload="document.getElementById('#fluidimage').style.width=newWidth; document.getElementById('#fluidimage').style.height=newHeight;"> 
    <img src="images/1.jpg" id="fluidimage" height="" width=""  />
</body>
</html>

您需要等待整个文档加载(最后加载图片),以便图像具有可检测的大小。

这段代码应该可以工作:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript" />

<script type="text/javascript">
    $(window).load ( function () {
        var width   = $("#fluidimage").width();
        var height  = $("#fluidimage").height();

        var imageresize = 80;
        var newHeight = Math.round(height*imageresize/100);
        var newWidth = Math.round(width*imageresize/100);

        $("#fluidimage").width (newWidth).height (newHeight);
    } );
</script>

</head>
<body> 
    <img src="images/1.jpg" id="fluidimage" />
</body>
</html>


在 jsFiddle 上查看它的实际效果。 http://jsfiddle.net/U9fyH/1/


请注意,数学需要在四舍五入之前进行。

此外,jQuery 允许您“简化”JS:

$(window).load ( function () {

    function resizer (index, measurement) {
        var imageresize = 80;
        this.wCall = (typeof this.wCall == "null") ? true : this.wCall ^ true;
        return this.wCall ? Math.round (measurement * imageresize / 100) : measurement;
    }
    $("#fluidimage").width (resizer).height (resizer);
} );


请参阅 jsFiddle 的实际情况。 http://jsfiddle.net/U9fyH/3/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 JQuery / javascript 创建动态图像:我做错了什么? 的相关文章