【问题标题】:auto fit image in div / jquery在 div / jquery 中自动调整图像
【发布时间】:2012-04-19 01:46:01
【问题描述】:

如果我的代码如下所示,如何自动调整图像:

<script type="text/javascript"> 
jQuery.noConflict();
jQuery(document).ready(function () {
    var count = 0;
    function animate() {
        jQuery(".fadein").eq(count).fadeIn(1000);
        count++;
        if(count <= jQuery(".fadein").length) {
            setTimeout(animate, 1000);
        } else {
            jQuery("a.fadein").fadeOut(1000);
            count = 0;
            animate();
        }      
    }
    animate();
});
</script>

这是正确的吗?

<script type="text/javascript"> 
    jQuery.noConflict();
    jQuery(document).ready(function () {
        var count = 0;
        function animate() {
            jQuery(".fadein").eq(count).fadeIn(1000);
            count++;
            if(count <= jQuery(".fadein").length) {
                setTimeout(animate, 1000);
            } else {
                jQuery("a.fadein").fadeOut(1000);
                count = 0;
                animate();
            }      
        }
        animate();
    })
            function fitImagetoContainer() {   $("img").each(function(i) {
     $(this).width($(this).parent().width()); //or your logic   
       }); }

//Call the function at load 
      $(window).load(function() {    fitImagetoContainer(); });


//Also call the function when the window resizes  
      $(window).resize(function() {    fitImagetoContainer(); });;
    </script>

【问题讨论】:

  • 我认为你在那里缺少一些标记。
  • 自动调整是什么意思?如果图像比容器小,比容器大,你希望发生什么?
  • @arasmussen:我的意思是,如果我调整浏览器的大小,那么图像也会跟随图像的大小。这可能吗?
  • @Marcel:我在 HTML 中做了一部分
  • 你能链接到你所拥有的演示吗? JavaScript 只是这个难题的一部分。例如,一些基本的 CSS 可能会解决您的问题。

标签: jquery html image image-size


【解决方案1】:

这是我对你的问题的看法

//Create a function to resize the image with respect to parent
function fitImagetoContainer() {
  $("img").each(function(i) {
     $(this).width($(this).parent().width()); //or your logic
  });
}

//Call the function at load
$(window).load(function() {
   fitImagetoContainer();
});


//Also call the function when the window resizes 
$(window).resize(function() {
   fitImagetoContainer();
});

【讨论】:

  • @tintincutes,是的,但在$(document).ready(); 部分之外
  • @tintincutes,是的,但是修复注释,它也在注释代码部分。
  • 我试过了,但它没有改变图像的大小。如果我调整浏览器的大小,图像超出范围。
  • 我在你的代码中读到了你的代码:$"img" - 我必须把图片的链接放在这里吗?
  • 不,它选择页面上的所有图像。你能在 jsfiddle.net 上创建一个你的页面的演示吗
【解决方案2】:

您需要添加 css。它更好,更易于维护。

只需将此添加到您的图像 css 中。

.fadein img {width: 100%; height: auto;} //This maintains the aspect ratio.

如果你想让图片无论如何都填满容器:

.fadein img {width: 100%; height: 100%;} //This distorts the image to fill the container

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 2020-04-21
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    相关资源
    最近更新 更多