如何修复我的页面上淡入/淡出部分的不一致Javascript代码



我使用的代码是在javascript fiddle项目中发现的,该项目根据查看器使用的页面内导航将各种#divID淡出页面。

我遇到的问题是每个按钮都会不一致地淡入/淡出内容。btn-one将平滑地淡出旧内容,平滑地淡出新内容,这正是我所希望的。按钮2和4将硬删除旧内容,并在新内容中淡入。按钮3将淡出旧内容,但在新内容中显示hard-cut

我希望他们都表现得一样。如果可能的话,我还希望能够控制div使用的每个动画的类型和持续时间。

我已经尝试过将fiddle代码直接复制/粘贴到我的项目中,它已经与两个div一起工作了。也许问题在于创建额外的div?但这引发了更多的问题,因为在小提琴中添加更多的div本身效果很好。

$('#btn-one').click(function(e) {
$('#reviews, #aboutus').fadeOut('slow', function() {
$('#splash').fadeIn('slow');
});
});
$('#btn-two').click(function(e) {
$('#splash, #aboutus').fadeOut('slow', function() {
$('#reviews').fadeIn('slow');
});
});
$('#btn-three').click(function(e) {
$('#splash, #reviews').fadeOut('slow', function() {
$('#aboutus').fadeIn('slow');
});
});
$('#btn-four').click(function(e) {
$('#splash, #reviews, #aboutus').fadeOut('slow', function() {
$('#even').fadeIn('slow');
});
});

我对两种结果之一持开放态度:

  1. 对现有代码的解决方案,以使事情正常工作
  2. 一个全新的代码解决方案,可以提供更好的结果

我感谢你能提供的任何帮助。非常感谢。

如果您想要更多的控制,请尝试使用CSS转换。您可以通过设置以下类来模拟fadeIn/Out()功能:

.fade {
opacity: 1;
transition: .3s;
}
.fade-out {
opacity: 0;
}
.hidden {
display: none;
}

然后用.toggle-btn类初始化所有按钮,用.fade类初始化div,除了要显示的类之外,所有按钮都包括.fade-out.hidden类(这将使它们隐藏起来)。然后附加一个事件侦听器(只在文档中添加一个,不需要为每个按钮单独添加一个),就像一样

const toggleBtns = {one: 'splash', two: 'reviews', three: 'aboutUs', four: 'even'}
document.addEventListener('click', e => {
// this line cancels the event if it's not a button we want
if (!e.target.classList.contains('toggle-btn')) return;
// grab the element(s) we want to hide
const toFade = $('.fade:not(.fade-out)');
// add an event listener for the CSS transition that removes after firing
toFade.one('transitionend', function(tansitionEvent) {
toFade.addClass('hidden')
});
// apply the class which will start the transition
toFade.addClass('fade-out');
// remove the invisibility classes from your target element, starting that transition
$(`#${toggleBtns[e.target.id.split('-')[1]]}`).removeClass('fade-out hidden');
}

我从未在JQuery中使用过transitionend,但我认为它是有效的。看起来你希望你的按钮只显示一件事,而隐藏其他一切,所以我把相关的div ID放在一个对象中。然后我用toggleBtns[e.target.id.split('-')[1]]抓住它。您为按钮ID维护btn-number的模式,所以我使用split()来获取数字,然后将结果作为键传递到toggleBtns对象中。

最新更新