我有以下菜单系统代码,其中包含每个菜单项中常见的许多部分。
我正在努力将通用代码放入函数中,然后我可以根据需要调用这些函数 - 因此我不需要数百行相同的代码。
有人能帮我指出正确的方向吗?
$("#test1").hover( function() {
$(this).animate({
width: "599px",
left: "0px",
height: "168px",
backgroundColor: "#d7df23",
opacity: 0.95
}, 100).css({'z-index': "10", 'border-top': 'none'});
// Start of common code
$(this).find(".thumb").animate({
width: "150px",
height: "150px",
marginTop: "8px",
marginRight: "0px",
marginBottom: "0px",
marginLeft: "12px"
}, 100).attr('src','images/home/animatedMenu/1IMG.jpg').css({'border': '1px solid #FFF'});
// End of common code
$(this).find("h2").animate({
left: "600px"
}, 100).hide();
$(this).find(".moredetail").delay(150).animate({
left: "0px"
}, {
duration: 150,
easing: 'easeInBounce'
});
}, function() {
$(this).clearQueue().animate({
width: "246px",
left: "9px",
height: "83px",
backgroundColor: "#222",
opacity: 0.90
}, 100).css({'z-index': "1", 'border-top': '1px solid #444'});
// Start of common code
$(this).find(".thumb").animate({
width: "68px",
height: "68px",
marginTop: "6px",
marginRight: "0px",
marginBottom: "0px",
marginLeft: "13px"
}, 100).attr('src','images/home/animatedMenu/1IMGup.jpg').css({'border': '1px solid #000'});
// End of common code
$(this).find("h2").show().animate({
left: "0px"
}, {
duration: 350,
easing: 'easeOutBounce'
});
$(this).find(".moredetail").animate({
left: "600px"
}, 100);
});
最佳答案
将每个重用的代码片段分解到函数中。您将拥有两个像这样的函数:
function thumbHoverStart(element) {
$(element).find(".thumb").animate({
width: "150px",
height: "150px",
marginTop: "8px",
marginRight: "0px",
marginBottom: "0px",
marginLeft: "12px"
}, 100)
.attr('src','images/home/animatedMenu/1IMG.jpg')
.css({'border': '1px solid #FFF'});
}
从适当的事件调用每个函数:
// ...
opacity: 0.95
}, 100).css({'z-index': "10", 'border-top': 'none'});
thumbHoverStart(this);
$(this).find("h2").animate({
left: "600px"
// ...
关于javascript - Jquery - 为常见任务编写函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3940821/