【问题标题】:jQuery image/window resize--max resize constraintjQuery 图像/窗口调整大小--最大调整大小约束
【发布时间】:2017-01-03 12:03:14
【问题描述】:

我目前有一个页面,其中我有固定大小的 div,当用户向下滚动时加载页面(类似于 Infinite Scroll),并且目前正在开发使加载的图像和容器随浏览器窗口一起动态调整大小的功能。我目前的问题是我目前正在使用$(window).width$(window).height,这自然会导致图像调整为窗口宽度。

我想知道我可以设置什么 maxWidthmaxHeight 以使图像的大小不会超过其原始大小?我一直在使用$(window) 来测试功能,但我基本上不希望图像变得比原始尺寸大。我试过$(this),但它导致比率等于1,导致没有调整大小。

    $(window).resize(function () {
        imageResize();
    });

    function imageResize() {
        $(".added").each(function () {
                var maxWidth = $(window).width();
                var maxHeight = $(window).height();
                var ratio = 0;
                var width = $(this).width();
                var height = $(this).height();

                if (width > maxWidth) {
                    ratio = (maxWidth / width);
                    $(this).width(maxWidth);
                    $(this).height(height * ratio);
                    $(this).parent().height(height * ratio);
                    $(this).parent().width(maxWidth);   
                } else {
                    ratio = (maxWidth / width);
                    $(this).width(maxWidth);
                    $(this).height(height * ratio);
                    $(this).parent().height(height * ratio);
                    $(this).parent().width(maxWidth);   
                }
        });
    }

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您希望将max-heightmax-width 属性设置为您所说的值,这不会强制图像增长超过其原始高度或宽度,并且如果它更大,则会将其最小化。

    用途:

    $("#imageId").attr("max-width",maxWidth);
    $("#imageId").attr("max-height",maxHeight);
    

    【讨论】:

    • 所以我应该将maxHeightmaxWidth 设置为$(this).width()$(this).height()。我不确定哪些选择器可以让我将所需的原始尺寸设置为最大值。
    • 取决于您要为图像提供的宽度和高度。你想要什么宽度/高度?
    【解决方案2】:

    我会改变风格: ($this).style.maxWidth = maxWidth;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2017-04-29
      • 2021-10-02
      • 2019-06-17
      • 2012-08-07
      • 2012-04-07
      相关资源
      最近更新 更多