【问题标题】:Image native width in jqueryjquery中的图像本机宽度
【发布时间】:2010-12-11 06:14:44
【问题描述】:

使用 jQuery,我可以在单击时更改图像的 src

$("#thumb li img").click(function() {
var newlinkimage = $(this).attr("src");

newlinkimage = newlinkimage.substring(14,17);

    $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg');
    $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg');

问题是,新的图像宽度与旧的不同。我如何获得新图像的 NATIVE 宽度(就像在 dreamweaver 中获得的小箭头一样

【问题讨论】:

    标签: jquery image width


    【解决方案1】:

    这是执行此操作的普通 javascript 方式。应该很容易将其集成到您的代码中。

    var newimage = new Image();
    newimage.src = 'retouche-hr' + newlinkimage + '-a.jpg'; // path to image
    var width = newimage.width;
    var height = newimage.height;
    

    【讨论】:

    • 确保图像路径是实际图像的有效图像路径
    • 当您调用高度/宽度时,图像必须已经加载。第二行加载图像,但在第 3 行或第 4 行运行时可能尚未完成加载。
    • 问题是没有加载图像。我已经打开另一个问题并得到了答案:stackoverflow.com/questions/1645166/…
    【解决方案2】:

    旧图像是否设置了宽度和高度?如果您使用 $(image).width("") 它应该将宽度重置回您对其应用任何宽度更改之前的宽度(类似于高度)。我认为这不适用于通过 CSS 或属性设置宽度的图像。重置为旧宽度后,您可以使用 .outerWidth() 获取图像的宽度。

    【讨论】:

      【解决方案3】:

      您想在更改图像之前获取图像的实际宽度,然后将新图片设置为该宽度。你可以用 $(img).load 来做到这一点:

      var pic_real_width;
      var pic_real_height;
      
      $(img).load(function() {
          // need to remove these in of case img-element has set width and height
          $(this).removeAttr("width")
                 .removeAttr("height");
      
          pic_real_width = this.width;
          pic_real_height = this.height;
      });
      
      $("#thumb li img").click(function() {
      var newlinkimage = $(this).attr("src");
      
      newlinkimage = newlinkimage.substring(14,17);
      
              $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg').width(pic_real_width);
              $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg').width(pic_real_width);
      

      【讨论】:

        【解决方案4】:

        此代码始终返回零“0”

            var newimage = new Image();
            newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; 
            var width = newimage.naturalWidth;
            var height = newimage.naturalHeight;
            alert (width);
        

        为什么???

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-15
          • 2012-02-13
          • 2012-04-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多