[英]Set height and width of image inside div using javascript and jquery
我有一個問題,我想只使用Javascript和JQuery設置div內的圖像的高度和寬度。
這是我的代碼:
<div class="myGallery">
<img class="replaced" src="myimage.jpg" style="display: inline;">
</div>
.myGallery {
display: table-cell;
height: 220px;
text-align: center !important;
vertical-align: middle !important;
width: 110px;
}
.myGallery img {
text-align: center;
vertical-align: middle;
width: auto !important;
}
function ChangeHW(hdnValue)
{
if (hdnValue==1)
{
//i want to remove height and width attribute of image
//this is working..
$('div.myGallery > img').removeAttr('width');
$('div.myGallery > img').removeAttr('height');
}
else
{
//i want to set height and width attribute of image
//this is not working..i cant set width-height using this line od code
$('div.myGallery > img').css('width', '110px');
$('div.myGallery > img').css('height', '220px');
}
}
有任何想法嗎?
屬性與樣式不同。 假設您當前的圖片代碼如下所示:
<img src="foo.png" width="200" height="200" />
在$('div.myGallery > img').removeAttr('width')
,它將如下所示:
<img src="foo.png" height="200" />
您正在刪除width 屬性 。 現在在$('div.myGallery > img').css('width', '440px')
,它看起來像這樣:
<img src="foo.png" height="200" style="width: 440px;" />
你正在添加寬度,但它是CSS樣式而不是屬性。 試試這個:
$('div.myGallery > img').attr('width', '440');
這是一個將圖像擬合到586x586 div標簽的功能。
function img_fit(img_id){
var img_width = $("#"+img_id).width();
var img_height= $("#"+img_id).height();
var max_side = Math.max(img_width, img_height);
var top = 0, left = 0, scale = 0;
var new_width, new_height,new_scale;
scale = (max_side == img_height)? img_height/586 : img_width/586;
if(max_side == img_height){
new_width = img_width / scale;
new_height = 586;
top = 0;
left = Math.round((586 - new_width)/2);
$("#"+img_id).animate({
'width':new_width,
'height':new_height,
'top':0,
'left':left,
'duration':300
});
//$("#"+img_id).width(new_width);
//$("#"+img_id).height(586);
new_scale = 586*scale/img_height;
}
else{
new_height = img_height / scale;
new_width = 586;
top = Math.round((586 - new_height)/2);
//top = 0;
left = 0;
$("#"+img_id).animate({
'width':new_width,
'height':new_height,
'top':top,
'left':0,
'duration':300
});
}
}
嘗試這個:
$('div.myGallery > img').css('width', '110px !important');
$('div.myGallery > img').css('height', '220px !important');
您希望將圖像寬度設置為大於包含div,這可能是問題嗎?
喲刪除高度和寬度removeAttr
將在圖像標簽中設置<img src="puppies.jpg" width="100" height="100">
,否則,要在css中更改它,我會設置width
和height = auto
,或者如果你想讓容器確定大小,請嘗試width:100% height:auto
。 要添加高度和寬度,您的.css('width','440px')
應該有效。 但是如上所述,包含div更小。
也許這可以幫助:
.newCssClass { height : 110px !important; width : 440px !important; }
$("div.myGallery img").addClass("newCssClass");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.