【问题标题】:Scale image in div after load complete with jQuery使用 jQuery 加载完成后在 div 中缩放图像
【发布时间】:2011-02-18 05:16:09
【问题描述】:

我有一些缩略图,当你点击它们时,我有一个带有 DIV 的模态框,我想从更大的图像缩放 50% 的宽度/高度。

我想知道以下缩放方法对于 800x530 像素的图像是否有效且跨浏览器:

#foo-img { width: 100%; height: 100%; }
#foo-div {
    width: 400px; height: 265px;
    padding: 10px; background: black;
}
<div id="foo-div">
    <img id="foo-img" src="img/003.jpg" />
</div>

我似乎不能只设置 #foo-img 宽度/高度属性,因为每次加载新图像时它都会缩小 50%!

这是可行的,但对我来说似乎有很多代码:

var rnd = Math.floor(Math.random() * 101)

$("a.loadimg").click(function() {
    // resets the DIV
    imgLoadReset();
    var imgPath = "images/" + $(this).text() + "?" + rnd;
    imgLoad(imgPath);
    return false;
});

function imgLoad(imgPath) {
    $("#foo-img").hide()
        .one('load', function() {
            imgLoadComplete();
        })
        .attr("src", imgPath)
        .each(function() {
            if (this.complete) $(this).trigger('load');
        });
}

function imgLoadComplete() {
    // after the image is completely loaded, we can get the w/h of the image
    var imgW = $("#foo-img").width() / 2;
    var imgH = $("#foo-img").height() / 2;

    // set div to half image size           
    $("#foo-div").css({
        "width": imgW,
        "height": imgH
    });
    // this should scale the image inside the div
    $("#foo-img").css({
        "width": "100%",
        "height": "100%"
    });

    $("#foo-img").show();
}

function imgLoadReset() {
    // delete w/h attributes otherwise it doesn't work
    $("#foo-img").css({
        "width": "",
        "height": ""
    });
    // clear image with a blank
    $("#foo-img").attr("src", "about:blank");
}

HTML

<div id="foo-div">
    <img id="foo-img" src="about:blank" />
</div>
<hr>
<a class="loadimg" href="#">001.jpg</a> | 
<a class="loadimg" href="#">002.jpg</a> | 
<a class="loadimg" href="#">003.jpg</a> | 
<a class="loadimg" href="#">004.jpg</a>

【问题讨论】:

    标签: javascript jquery css image scale


    【解决方案1】:

    使用

    img {
        max-width: 100%;
        width: auto;
        height: auto;
    }
    

    为您的图像;指定其容器 div 的所需宽度(以像素为单位)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2023-04-06
      相关资源
      最近更新 更多