我正在尝试获得当前内容淡出的动画效果,然后替换为从屏幕右侧滑入的内容。我目前的努力:
<p>header</p>
<div id="wrapper">
<div style="height: 400px; background-color: red;">
<p>Here is some text!</p>
<button id="next">And a button!</button>
</div>
</div>
<p>footer</p>
$('#next').click(function () {
var current = $('#wrapper :first-child');
var next = $('<div>').css("height", "400px").css("background-color", "blue");
next.hide();
current.fadeOut(800, function () {
current.remove();
$('#wrapper').prepend(next);
next.show("slide", { direction: "right" }, 800);
});
});
两个问题:
- 被移除的元素仍在占用空间;注意页脚是如何向下推的。
- 有没有办法抑制水平滚动条?
如有任何关于更好的方法的提示,我们将不胜感激。谢谢!
最佳答案
垂直向后滚动的原因是因为 jQuery UI 放置了一个额外的 UI 包装器。
你可以用普通的 jQuery 做到这一点,它应该没问题:
$('#next').on('click',function(){
var wrapper = $('#wrapper'),
current = wrapper.children().first(),
next = $('<div>').css({
height:400,
backgroundColor:'blue',
marginLeft:'100%',
display:'none'
});
current.fadeOut(800, function () {
$(this).remove();
wrapper.prepend(next);
next.show().animate({marginLeft:0},800);
});
});
这是快速修复方法。另一个步骤是将您的 CSS 外部化到类中(您确实应该这样做而不是内联样式)以使事情变得更清晰:
HTML:
<p>header</p>
<div id="wrapper">
<div class="first">
<p>Here is some text!</p>
<button id="next">And a button!</button>
</div>
</div>
<p>footer</p>
CSS:
wrapper {
overflow:auto;
overflow-x:hidden;
}
.first {
height:400px;
background-color:red;
}
.second { 高度:400px; 背景色:蓝色;
更好的 jQuery:
$('#next').on('click',function(){
var wrapper = $('#wrapper'),
current = wrapper.children().first(),
next = $('<div>').addClass('second').css({
marginLeft:'100%',
display:'none'
});
current.fadeOut(800, function () {
$(this).remove();
wrapper.prepend(next);
next.show().animate({marginLeft:0},800,function(){
$(this).removeAttr('style');
});
});
});
Here is a second jsFiddle for that.
最后,最好的(尽管不兼容旧浏览器)方法是最大化 CSS。
CSS:
#wrapper {
overflow:auto;
overflow-x:hidden;
}
.first {
height:400px;
background-color:red;
}
.second {
height:400px;
background-color:blue;
margin-left:0;
-webkit-transition:margin-left 800ms;
-moz-transition:margin-left 800ms;
-o-transition:margin-left 800ms;
transition:margin-left 800ms;
}
.secondPushed {
margin-left:100%;
}
更小的 jQuery:
$('#next').on('click',function(){
var wrapper = $('#wrapper'),
current = wrapper.children().first(),
next = $('<div>').addClass('second secondPushed').hide();
current.fadeOut(800, function () {
$(this).remove();
wrapper.prepend(next);
next.show().removeClass('secondPushed');
});
});
从俯视的 Angular 来看,这是最好的,也是现代网络世界的方式,但它不适用于 IE9 及以下版本。
关于javascript - 为 HTML 内容创建淡出和滑入动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434296/