我遇到了这篇文章(http://stackoverflow.com/questions/10665918/jquery-animate-shake-on-hover)这几乎是我正在寻找的,这个jsfiddle(http:// jsfiddle .net / g6AeL / 222 /),但是当你将鼠标悬停在物品上时,我只需要将振动功能发生一次,而不是在你将鼠标悬停在物品上时不断振动。
当你将鼠标悬停在项目上时,有人可以帮助我做一次吗?
这是来自jsfiddle的javascript。
$(function() {
var interval = 10;
var duration= 1000;
var shake= 3;
var vibrateIndex = 0;
var selector = $('.box'); /* Your own container ID*/
$(selector).each(function(){
var elem = this;
$(this).hover( /* The button ID */
function(){
vibrateIndex = setInterval(function(){
vibrate(elem);
}, interval);
},
function(){
clearInterval(vibrateIndex);
$(this).stop(true,false)
.css({position: 'static', left: '0px', top: '0px'});
}
);
})
var vibrate = function(elem){
$(elem).stop(true,false)
.css({position: 'relative',
left: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px',
top: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'
});
}
});
答案 0 :(得分:1)
您可以像这样添加一个计数器:
var Counter = 0
var vibrate = function(elem){
if (Counter <= 100) {
Counter++;
$(elem).stop(true,false)
.css({position: 'relative',
left: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px',
top: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'
});
}
}
它会根据你的需要振动多次然后停止。您需要在某些可以选择的事件上重置计数器,例如mouseout等。
答案 1 :(得分:1)
你可以尝试添加一个setTimeout来阻止有时发抖。
也许是这样的:
$(selector).each(function(){
var elem = this;
var vibrateIndex;
var timeoutIndex;
$(this).hover( /* The button ID */
function(){
vibrateIndex = setInterval(function(){
vibrate(elem);
}, interval, 0);
timeoutIndex = setTimeout(function(){clearInterval(vibrateIndex)},1000);
},
function(){
clearInterval(vibrateIndex);
clearTimeout(timeoutIndex);
}
);
})
查看jsfiddle
答案 2 :(得分:0)
好的我开始制作它的插件:
$.fn.extend({
randShake : function(duration, shakeInt,shake){
return $(this).stop(true,false)
.css({
left : Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px',
top : Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'
}).vibrate(duration, shakeInt,shake);
},
vibrate : function(duration, shakeInt,shake) {
if (duration>shakeInt) setTimeOut(function(){
$(this).randShake(duration-shakeInt, shakeInt,shake);
},shakeInt);
}
return this;
}
});
jQuery(function($,undefined) {
$(selector).on("mouseover",function(){
$(this).vibrate(duration, shakeInt,shake);
});
})
还没有对它进行测试,但这个想法在我看来更像是jquery而不是原始代码