我怎样才能提高这个jQuery动画代码
问题描述:
我已经写了一些代码,当我将鼠标悬停在一个元素,增加了它周围的四个箭头,并让他们搬回并转发循环动画中的表现。我怎样才能提高这个jQuery动画代码
这是为了直观地表明元素是可拖动的。我使用hoverIntent
插件只在用户打算悬停在元素上时绘制箭头。我也使用jQueryUI进行元素定位。
附加到文件的项目,然后设置其动画是我以前从未尝试过,我敢肯定,我已经编写这个不好导致性能不太理想。
我怎么能让这段代码更好地执行?
jQuery.fx.interval = 1;
// Add Hover arrows
$('.table-row.songnamecolumn').livequery(function($songRow) {
var $songRow = $(this).closest('tr').children('td');
var $appenditem = $(this);
var $this = $(this);
var loop = function loop(){
$('#toparrow').animate({ top:'-=15px'},500).animate({ top:'+=15px'},100);
$('#bottomarrow').animate({ top:'+=15px'},500).animate({ top:'-=15px'},100);
$('#leftarrow').animate({ left:'-=15px'},500).animate({ left:'+=15px'},100);
$('#rightarrow').animate({ left:'+=15px'},500).animate({ left:'-=15px'},100);
}
$(this).hoverIntent({
sensitivity: 3, // How sensitive the hoverIntent should be
interval: 200, // How often in milliseconds the onmouseover should be checked
over: slidedrag, // Function to call when mouseover is called
timeout: 200, // How often in milliseconds the onmouseout should be checked
out: slidedragback // Function to call when mouseout is called
});
function slidedrag() {
$('<div id="toparrow"></div>'
+'<div id="leftarrow"></div>'
+'<div id="rightarrow"></div>'
+'<div id="bottomarrow"></div>').appendTo($appenditem);
$('#toparrow').position ({
of: $this,
my: 'center top',
at: 'center top',
offset: "0 -18"
})
$('#bottomarrow').position ({
of: $(this),
my: 'center bottom',
at: 'center bottom',
offset: "0 18"
})
$('#leftarrow').position ({
of: $(this),
my: 'left center',
at: 'left center',
offset: "-10 0"
})
$('#rightarrow').position ({
of: $(this),
my: 'right center',
at: 'right center',
offset: "10 0"
})
$('#toparrow, #bottomarrow, #leftarrow, #rightarrow').animate({opacity:'0.5'},600);
setInterval(loop, 600);
}
function slidedragback() {
clearInterval(loop);
$('#toparrow, #bottomarrow, #leftarrow, #rightarrow').animate({opacity:'0'},600);
$('#toparrow,#bottomarrow,#leftarrow,#rightarrow').remove();
}
});
答
我看到你不止一次地选择了相同的元素。我建议你将其保存为局部变量和调用变量:
var arrow_top = $('#toparrow');
在白色的空间,你的代码块删除:
out: slidedragback // Function to call when mouseout is called
});
function slidedrag() {
末,避免做了动画。
谢谢你的建议Jeaffrey。我已经尝试将对象声明为变量,因为在编写jQuery时,这是我的常规做法。但是,由于某种原因,当我在循环中使用变量时,它似乎不起作用。任何想法,为什么这可能是? – gordyr
不要使用$符号作为变量前缀,例如。 'songRow'而不是'$ songRow' –
我一直使用$作为变量前缀。大多数情况下,当我声明一个将包含jQuery对象的变量时,我会使用它。 – David