我認爲這應該是一件簡單的事情,但我沒有看到明確的方法來實現它。如何在JavaScript中使圖像變大x%(使用jQuery)
我想這樣做,當用戶將鼠標懸停在圖像上時,圖像變大10%,然後在用戶移開鼠標時恢復到原始大小。
我想我會想用jQuery hover
函數,但是我不知道要傳入什麼函數hover
。
$('.resizableImage').hover(makeBigger, returnToOriginalSize);
我認爲這應該是一件簡單的事情,但我沒有看到明確的方法來實現它。如何在JavaScript中使圖像變大x%(使用jQuery)
我想這樣做,當用戶將鼠標懸停在圖像上時,圖像變大10%,然後在用戶移開鼠標時恢復到原始大小。
我想我會想用jQuery hover
函數,但是我不知道要傳入什麼函數hover
。
$('.resizableImage').hover(makeBigger, returnToOriginalSize);
jQuery允許您使用+=
和%
。所以這兩個人會一起做你想做的。
$('.resizableImage').hover(makeBigger, returnToOriginalSize);
function makeBigger() {
$(this).css({height: '+=10%', width: '+=10%'});
}
function returnToOriginalSize() {
$(this).css({height: "", width: ""});
}
這很好用! 我不知道如果我可以使用顯示CSS屬性之一,以防止其他圖像被「推」到一邊,因爲一個圖像被放大... –
@DanielAllenLangdon:我敢肯定你可以。不知道如何脫手。 –
你可以用CSS3等轉換財產做,例如
$('.resizableImage').hover(function(){
$(this).css("transform", "scale(1.1, 1.1)");
}, function(){
$(this).css("transform", "none");
});
我在Internet Explorer 8和Firefox 14中試過這個。它不起作用。也許這個CSS在我運行的版本中不受支持?我使用調試器進行了仔細檢查,發現我的jQuery選擇器是頁面上的匹配元素。 –
如果你在該元素上存在'transform',它也會中斷,因爲在mouseout上它將被刪除。你不需要jquery這個效果btw。,風格'.resizableImage:hover'就夠了 –
是的,我的壞。轉換有點棘手,afaik你需要爲不同的瀏覽器添加不同的標籤(http://www.w3schools.com/cssref/css3_pr_transform.asp) – shiftoff
沒有CSS3,你可以使用.width()
和.height()
方法簡單地得到原來的大小,將其存儲在數據屬性(S)和調整大小。在mouseout上恢復原始值。
var hoverRatio = 1.1;
$('.resizableImage').hover(function() {
$(this).data('width', $(this).width());
$(this).data('height', $(this).height());
$(this).css({
width: $(this).width() * hoverRatio,
height: $(this).height() * hoverRatio
});
}, function() {
$(this).css({
width: $(this).data('width'),
height: $(this).data('height')
});
});
查看DEMO。
如果你不使用內聯樣式,你可以省略數據保存舊值,並使用風格ATTR代替。
$('.element').hover(function() {
var el = $(this);
el.attr('style','width:'+el.width() * 1.1 + 'px;height:'+el.height() * 1.1 + 'px;');
}, function() {
$(this).removeAttr('style');
});
你應該停止使用上的動畫也因此它不會當用戶在動畫finsihed
HTML之前移出打斷:
<img src="http://placehold.it/350x150" class="resizableImage" width="350" height="150" />
JS:
$('.resizableImage').mouseenter(function() {
$(this).stop().animate({ width: "+=10%", height: "+=10%" });
});
$('.resizableImage').mouseleave(function() {
var x = $(this).attr('width'),
y = $(this).attr('height');
$(this).stop().animate({ width: x, height: y });
});
這裏是一個小提琴: http://jsfiddle.net/tWdAK/1/
你不能只是做這個用CSS:
CSS
.resizable_img {
position: relative; // needed for z-index to work
width: 100%;
height: auto; // will resize image proportionally
}
.resizable_img:hover {
width: 120%;
z-index: 1; // place image on top
}
.img_container {
width: 25%;
position: relative;
overflow: visible; // stops images being shifted
float:left;
}
HTML
<div class="contents">
<div class="img_container">
<img class="resizable_img" src="img.jpg">
</div>
</div>
小提琴here
感謝,工作在被動頁面加載即「/#」正在殺死Jquery的情況下。低科技,讚賞。 – twobob
我認爲修改CSS,但最a我能想到的東西很快就會變得複雜起來。我認爲必須有一個簡單的方法來做這樣的事情。 –