简体   繁体   English

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

[英]getting the image width from the href tag instead from img tag

i am working on a project in which i require the width of a image from href when i click on the specific image the width if the image displays in a alert . 我正在一个项目中,当我单击特定图像时,如果图像显示在警报中,则需要从href来获得图像的宽度。

the following is the href and image code i am using 以下是我正在使用的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>

whenever i try to get the width of the image it takes the image width from the img tag not from the href . 每当我尝试获取图像的宽度时,它都会从img标签而不是href中获取图像宽度。 as the img tag width is already defined "160" . 因为img标签的宽度已经定义为“ 160”。 is there a way possible for getting the width of the image from the <a href 有没有办法从<a href获取图像的宽度

i am using the following code which is nit working 我正在使用以下有效的代码

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

the html code 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>           

Based on something like: 基于类似:

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

This should do it: 应该这样做:

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

Update : If you need to continue your program using the width/height, try: 更新 :如果您需要使用宽度/高度继续执行程序,请尝试:

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...
}

You don't need to append the temporary image to the document, but you do need to add a load listener before you extract width/height. 您不需要将临时图像附加到文档,但是您需要在提取宽度/高度之前添加负载侦听器。

Remember that the AdBlock extension can affect the outcome of the extraction in webkit, so please turn it off when debugging. 请记住,AdBlock扩展名可能会影响webkit中提取的结果,因此请在调试时将其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM