asp.net mvc 3 mixing jquery and razor to get and set the image width
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());
});
});
精彩评论