【问题标题】:Getting image height after image has been resized using css and jquery?使用css和jquery调整图像大小后获取图像高度?
【发布时间】:2012-03-13 07:14:20
【问题描述】:

我有点卡住了。我正在用 jquery 和 css 创建一个旋转的背景图像。我根据浏览器大小调整图像宽度,但我不想改变高度,因为它会扭曲图片。所以我想做一个简单的数学方程,使图像垂直居中在屏幕上。例如:图像的原始尺寸为 1600 像素,它调整为 1200 像素,我需要获取调整后图像的高度。我用 jquery simple 试过这个: $("#img1").height();但它返回值 0。这是我的 jquery、html 和 css:

HTML

<div id="div2"><img src="images/1.jpg" class="bg" id="img1" /></div>
<div id="div3"><img src="images/1-blur.jpg" class="bg"/></div>
<div id="content">Body Content goes here!!</div>

<script>
var iheight = $("#img1").height();
$("#content").append(iheight);
</script>

CSS 身体{ 填充:0; 边距:0; 位置:相对; 溢出:隐藏; } .bg { 宽度:100%; 位置:绝对; 顶部:0; 左:0; z-index:1; } #内容{ 位置:相对; z指数:999; }

和 Jquery 来旋转图像:

$(window).load(function(){
function startfade(){

$("#div3").fadeIn(3000, function(){
    $(this).delay(2000).fadeOut(2000);
    $("#div2").fadeIn(3000, function(){
        $(this).delay(2000).fadeOut(2000);
});
});

}
setInterval(function() {
      startfade();
}, 6000);


startfade();


});

任何有关如何获取图像实际高度的帮助都会很棒!非常感谢!

【问题讨论】:

    标签: jquery css image resize


    【解决方案1】:

    尝试在加载图像时调用 height(并且您应该始终将您的代码包含在 $(function() {}); 中,以便在 DOM 准备好时调用您的代码)

    $(function() {
       $('#img1').load(function() {
           $("#content").append($(this).height());
       });
    });
    

    【讨论】:

      【解决方案2】:

      这是我在 stackflow 上找到的类似线程的答案。希望对您有所帮助!

      var img = $("img")[0]; // Get my img elem
      var pic_real_width, pic_real_height;
      $("<img/>") // Make in memory copy of image to avoid css issues
          .attr("src", $(img).attr("src"))
          .load(function() {
              pic_real_width = this.width;   // Note: $(this).width() will not
              pic_real_height = this.height; // work for in memory images.
          });
      

      【讨论】:

      【解决方案3】:

      我用这个公式,得到原图的高宽比

      var ratio=originalImageHeight/originalImageWidth;
      var newHeight=newWidth * ratio;
      

      【讨论】:

        猜你喜欢
        • 2018-01-07
        • 2012-03-08
        • 1970-01-01
        • 2014-03-24
        • 1970-01-01
        • 1970-01-01
        • 2013-09-14
        • 2014-10-14
        • 2013-04-30
        相关资源
        最近更新 更多