【问题标题】:Getting client side image width of dynamic image with jquery使用jquery获取动态图像的客户端图像宽度
【发布时间】:2015-08-11 05:56:49
【问题描述】:

我正在尝试编写一个灯箱,在单击 div 时在容器内显示图像。

所说的 div 将实际图像显示为背景图像,用作缩略图。

这些图像将由用户加载,因此我没有它们的实际宽度和高度。

所以我有一堆以图像为背景的 div 和一个带有容器、图像(带有空 src)和描述的灯箱,每次单击缩略图时都会显示。

为此,我使用了这个:

//设置灯箱图片和描述

            var imageToDisplay =    $(this).siblings(".selfieImage")
                                    .css("background-image")
                                    .replace(/"/g, "")
                                    .replace(/url\(|\)$/ig, "");

            var descToDisplay =     $(this).siblings(".selfieImage")
                                    .attr("data-description");

            $('.lightBoxImage').attr('src', imageToDisplay);
            $('.lightBoxDescription').text(descToDisplay);

问题是我不知道描述会有多长,并且容器的宽度没有设置,因为它将占用其较大元素的宽度。但是,它的高度始终是屏幕的 50%,因此图像会改变其原始大小。

我想将生成的图片的宽度设置为容器的宽度,所以描述文字会在图片底部换行。

我该怎么做?我在这里阅读了很多答案,但这些似乎都不起作用,因为我在加载页面时已经用 0,0 维度创建了我的灯箱图像。我只是在更改它的源,所以 onload 和 ready 函数没有按预期工作。

【问题讨论】:

    标签: javascript jquery html css image


    【解决方案1】:

    据我了解,您可以尝试创建图像对象并在onload 处理程序中,设置容器宽度和.lightBoxImagesrc,如下所示。

    var image = new Image();
    image.onload = function(){ // always fires the event when the image is loaded.
        $('containerSelector').css({
            width: image.width;
        });
        $('.lightBoxImage').attr('src', imageToDisplay);
    };
    // handle failure
    image.onerror = function() {};
    // set the src
    image.src = imageToDisplay;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 2012-04-04
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      相关资源
      最近更新 更多