我在加载后定位图像(以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});
}
});
});
答案 0 :(得分:0)
使用position
属性以及left
或top
$(".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'});
}
});