从href标记而不是img标记获取图像宽度


getting the image width from the href tag instead from img tag

我正在处理一个项目,在该项目中,当我单击特定图像时,我需要href中的图像宽度——如果图像显示在警报中,则宽度。

以下是我使用的href和图像代码

    <li>
      <a href="<?php echo $pic;?>?id=<?php echo $id;?>&pic=<?php echo $picID;?>" data-title="" data-desc=" " data-rel="group2" data-bw="<?php echo $pic;?>"  class="lightbox" id="plzx" >
      <img src="<?php echo $pic;?>"  width="160" height="160" title="Click To View"/></a>                       
    </li>

每当我试图获取图像的宽度时,它都会从img标记中获取图像宽度,而不是从href中获取。因为img标记宽度已经定义为"160"。有没有办法从<a href 中得到图像的宽度

我正在使用以下代码,它是不工作的

   $('a').click(function() {
       var image = $("<img />").attr("src", $(".lightbox").attr("href"));
       $(document).append(image);
       alert(image.height());
       alert(image.width());
       image.remove();
    });

html代码

       <li>
                    <a href="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg?id=3&pic=101" data-title="" data-desc=" " data-rel="group2" data-bw="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg"  class="lightbox" id="plzx" >
                    <img src="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg"  width="160" height="160" title="Click To View"/></a>
    </li>           

基于以下内容:

<a href="/path/to/big.jpg"><img src="/path/to/small.jpg"></a>

这应该做到:

$('a').click(function() {
    $(new Image()).load(function() {
        alert(this.width); // image width
        alert(this.height); // image height
    }).attr('src', this.href);
});

更新:如果您需要使用宽度/高度继续您的程序,请尝试:

var width,height;
$('a').click(function() {
    $(new Image()).load(function() {
        width = this.width;
        height = this.height,
        onLoaded();
    }).attr('src', this.href);
});
function onLoaded() {
    alert(width);
    alert(height);
    // continue...
}

您不需要将临时图像附加到文档中,但在提取宽度/高度之前,您确实需要添加一个加载侦听器。

请记住,AdBlock扩展可能会影响webkit中提取的结果,因此在调试时请将其关闭。