gpt4 book ai didi

javascript - 简化糟糕的 jQuery

转载 作者:行者123 更新时间:2023-11-28 14:56:35 25 4
gpt4 key购买 nike

想知道是否有人可以帮我简化这部分 jQuery:

$('.fixed-booking').on('mouseenter', function () {
var booking = $('.fixed-booking'),
tabHeight = $('.fixed-booking .nav-tabs').outerHeight(),
contentHeight = $('.fixed-booking .tab-content').outerHeight(),
bothHeight = tabHeight + contentHeight
;
booking.css({
'transform': 'translate(0,-' + bothHeight + 'px)'
});
});

$('.fixed-booking').on('mouseleave', function () {
var booking = $('.fixed-booking'),
tabHeight = $('.fixed-booking .nav-tabs').outerHeight(),
contentHeight = $('.fixed-booking .tab-content').outerHeight(),
bothHeight = tabHeight + contentHeight
;
booking.css({
'transform': 'translate(0,-' + tabHeight + 'px)'
});
});

$('.fixed-booking .nav-tabs a').on('click', function () {
var booking = $('.fixed-booking'),
tabHeight = $('.fixed-booking .nav-tabs').outerHeight(),
contentHeight = $('.fixed-booking .tab-content').outerHeight(),
bothHeight = tabHeight + contentHeight
;
booking.css({
'transform': 'translate(0,-' + bothHeight + 'px)'
});
});

此外,当单击导航栏选项卡之一时,只有单击两次,位置才会发生变化。

提前致谢:)

最佳答案

除了最终使用的高度之外,我没有看到每个处理程序之间有任何差异。您可以将其变成一个函数:

function setHeight(both) {
var booking = $('.fixed-booking'),
tabHeight = $('.fixed-booking .nav-tabs').outerHeight(),
contentHeight = $('.fixed-booking .tab-content').outerHeight(),
bothHeight = tabHeight + contentHeight
;
newHeight = both ? bothHeight : tabHeight;
booking.css({
'transform': 'translate(0,-' + newHeight + 'px)'
});
}

$('.fixed-booking').on('mouseenter', function() {setHeight(true)});
$('.fixed-booking').on('mouseleave', function() {setHeight(false)});
$('.fixed-booking .nav-tabs a').on('click', function() {setHeight(true)});

正如 Pango 所提到的,您可能希望进一步推广 setHeight 函数,以使基本选择器 (.fixed-booking) 更易于配置。这是 higher order functions 的一个很好的案例。 .

关于javascript - 简化糟糕的 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42652396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com