加载后的图像定位

时间:2013-05-27 06:33:26

标签: jquery asp.net asp.net-mvc

我在加载后定位图像(以div容器为中心)时遇到问题。我使用的Javascript代码适用于PHP,但有一个问题,可能是因为我使用了Url.Action。有些图像移动,有些则停留。

              foreach(GetFriendsItem hItem in (List<GetFriendsItem>)Model)
              {
                  Html.RenderPartial("~/Views/Users/_UserProfile.cshtml", hItem );
              }

/Views/Users/_UserProfile.cshtml

<img src="@Url.Action("Show", "Image", new { id = @Model.m_unUserID })" class="imageNarrowly image" />

的javascript

 $(function() {

    $(".image").load(function(index, val){
      // dimensions of the image
      var imageWidth = $(this).width();
      var imageHeight = $(this).height();

      var parentHeight = $(this).parents($(this).parent).height();
      var parentWidth = $(this).parents($(this).parent).width();


      if (parentHeight > imageHeight){
        topOffset = (parentHeight/2 - imageHeight/2);
        $(this).css({'top': topOffset}); 
      }

      if (parentWidth > imageWidth){
        leftOffset = (parentWidth/2 - imageWidth/2);
        $(this).css({'left': leftOffset}); 
      }
    });


  });

1 个答案:

答案 0 :(得分:0)

使用position属性以及lefttop

$(".image").load(function(index, val){
  // dimensions of the image
  var imageWidth = $(this).width();
  var imageHeight = $(this).height();

  var parentHeight = $(this).parent().height();
  var parentWidth = $(this).parent().width();


  if (parentHeight > imageHeight){
    topOffset = (parentHeight/2 - imageHeight/2);
    $(this).css({'top': topOffset,'position':'relative'}); 
  }

  if (parentWidth > imageWidth){
    leftOffset = (parentWidth/2 - imageWidth/2);
    $(this).css({'left': leftOffset,'position':'relative'}); 
  }
});
相关问题