我的目标是在鼠标悬停时将图像动画化为新的尺寸,并临时添加一个新的css类,并在鼠标移出时将其恢复为原始尺寸(并删除添加的类)。
我的代码在鼠标悬停时运行良好。鼠标移出时,添加的类将被删除,但是图像尺寸不会恢复为原始的宽度和高度。
HTML:
<img src='img.jpg' alt='' class='pulse'>jQuery:
$(function() {
// set global img width and height
var width_pulse_img = 0;
var height_pulse_img = 0;
$('img.pulse').hover(function () {
// onMouseOver: read original width and height on FIRST mouseover
if (!width_pulse_img) width_pulse_img = $(this).css('width');
if (!height_pulse_img) height_pulse_img = $(this).css('height');
// set img expansion ratio and compute new dimensions
var float_exp = 1 + 0.1;
var ww = (float_exp*parseInt(width_pulse_img, 10)).toString();
var hh = (float_exp*parseInt(height_pulse_img, 10)).toString();
// animate to new dimensions
$(this).addClass('hover').stop().animate({
width: ww + 'px',
height: hh + 'px'
}, 200);
}, function () {
// onMouseOut: animate back to original dimensions:
$(this).removeClass('hover').stop().animate({
// THIS IS THE PART THAT DOES NOT WORK
width: width_pulse_img + 'px',
height: height_pulse_img + 'px'
}, 400);
});
});我在Firefox12.0,Chrome和IE9.0上测试过,结果都是一样的。
这是一个演示问题的jsFiddle。任何帮助都将不胜感激。
发布于 2012-06-23 18:25:26
使用.width()和.height()而不是.css(..)可以做到这一点。所以像这样使用它
width_pulse_img = $(this).width();
height_pulse_img = $(this).height();而且它会工作得很好。
演示: http://jsfiddle.net/joycse06/z6zvg/1/
至于为什么失败,我仍然不确定为什么会发生这种情况。但在使用.css()时,它总是保留width and height中的更改。
更新:背后的原因
正如医生在.width()中所说的那样
.css(width)和.width()之间的区别在于,后者返回的是单位较少的像素值(例如,400),而前者返回的值是,单位保持不变(例如,400px)。
所以在第一次分配了这两行之后
width_pulse_img = $(this).css('width'); // 220px
height_pulse_img = $(this).css('height'); // 237px就像你用过.css(一样,他们已经有了px。
当你使用它的时候
width: width_pulse_img + 'px', // becoming 220pxpx
height: height_pulse_img + 'px' // 237pxpx因此,它忽略了整个事情,没有收缩图像。但是,由于您已经使用了parseInt,所以expanding工作得很好。
使用.css()的工作版本: http://jsfiddle.net/joycse06/z6zvg/4/
https://stackoverflow.com/questions/11168694
复制相似问题