开发者

asp.net mvc 3 mixing jquery and razor to get and set the image width

开发者 https://www.devze.com 2023-04-02 06:41 出处:网络
I am trying to specifically set an image inline width attribute to it\'s value, so I am trying to do that with jquery and razor, but I keep getting the initialized value - 100;

I am trying to specifically set an image inline width attribute to it's value, so I am trying to do that with jquery and razor, but I keep getting the initialized value - 100;

Code:

 @{
 var width = "100";
 }


     <script type="text/javascript">
     $(document).ready(function () {

        $('.tab-item-photo img').each(function () {
            width = $(this).width();
            alert(width);
        });


     });

     </script>


 <div class="tab-item-photo"><img src="@Url.Content("~/_files/149471/images/1712frnt.JPG")" width="@width" height="140px" /></div>

EDIT:

If I could do something like this:

<div class="tab-item-photo"><img src="@Url.Content("~/_files/149471/images/1712frnt.JPG开发者_如何学Go")"
width="$(this).width()" height="140px" /></div>

it would be great!


I think you want something like:

 @{
   //var width = "100"; not needed
 }

     <script type="text/javascript">
     $(document).ready(function () 
     {
        $('.tab-item-photo img').each(function()
        {
          var img = new Image();
          img.src = $(this).attr("src");
          $(this).attr("width", img.width);
        });
     });

     <div class="tab-item-photo">
       <img src="@Url.Content("~/_files/149471/images/1712frnt.JPG")" 
            width="1" height="1" /></div>


try $(this).attr('width'); to get attribute value.

.width() are using offcetWidth property of element, not attribute. Maybe it should be image loaded but on $(document).ready() it's still not.

EDIT:

Maybe you need to bind image load event and change the width:

$(document).ready(function () {
    $(".tab-item-photo img").load(function () {
        $(this).attr('width', $(this).width());
    });
}); 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号