平滑不稳定的jquery动画
Smooth out shaky jquery animations
我有一个在父元素内部旋转和反弹的图像。我做得很好,预计轮换会有点困难。刚开始的几秒钟是平稳的,然后开始有点摇晃。
我该如何解决这个问题?
$.fn.bounce = function(options) {
var settings = $.extend({
speed: 10
}, options);
return $(this).each(function() {
var $this = $(this),
$parent = $this.parent(),
height = $parent.height(),
width = $parent.width(),
top = Math.floor(Math.random() * (height / 2)) + height / 4,
left = Math.floor(Math.random() * (width / 2)) + width / 4,
vectorX = settings.speed * (Math.random() > 0.5 ? 1 : -1),
vectorY = settings.speed * (Math.random() > 0.5 ? 1 : -1);
// place initialy in a random location
$this.css({
'top': top,
'left': left
}).data('vector', {
'x': vectorX,
'y': vectorY
});
var move = function($e) {
var offset = $e.offset(),
width = $e.width(),
height = $e.height(),
vector = $e.data('vector'),
$parent = $e.parent();
if (offset.left <= 0 && vector.x < 0) {
vector.x = -1 * vector.x;
}
if ((offset.left + width) >= $parent.width()) {
vector.x = -1 * vector.x;
}
if (offset.top <= 0 && vector.y < 0) {
vector.y = -1 * vector.y;
}
if ((offset.top + height) >= $parent.height()) {
vector.y = -1 * vector.y;
}
$e.css({
'top': offset.top + vector.y + 'px',
'left': offset.left + vector.x + 'px'
}).data('vector', {
'x': vector.x,
'y': vector.y
});
setTimeout(function() {
move($e);
}, 50);
};
move($this);
});
};
$(function() {
$('#wrapper li').bounce({
'speed': 7
});
});
$(function() {
var $elie = $("img");
rotate(0);
function rotate(degree) {
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
timer = setTimeout(function() {
rotate(--degree);
},30);
}
});
JS FIDDLE
您的方法中的波动来自超时值50。一个简单的优化就是去除该间隔并调整矢量变化以保持速度不变。
setTimeout(function() {
move($e);
}, 0);
vectorX = settings.speed * (Math.random() > 0.5 ? 0.1 : -0.1),
vectorY = settings.speed * (Math.random() > 0.5 ? 0.1 : -0.1);
http://jsfiddle.net/k3uvb5c0/6/
相关文章:
- 如何简化动画jQuery代码
- 如何禁用可排序动画 Jquery
- 离开页面前的动画JQuery
- 动画Jquery弹出菜单
- 设置元素动画jquery
- 如何自动动画jquery画廊
- 缩放/动画 jQuery 拖放到可拖放时可拖动
- 卡片动画Jquery和CSS
- 拆分襟翼文本动画 Jquery
- 满足条件时禁用动画 jQuery
- 传递参数以动画 jquery 函数
- 延迟和动画 jQuery
- 获取动画 jQuery Java 脚本中行进的像素数
- 重新启动动画jquery和javascript
- 为什么这个脚本在页面加载后3秒没有动画(jquery)
- 菜单图标动画jQuery
- 制作无限动画jQuery
- 将延迟应用于动画jquery
- 添加滑动回调动画Jquery
- 使用动画 jquery 更改文本