我想在使用 slideToggle()
时逐步减少我的容器 magin
$(document).ready(function() {
$("#btn").click(function() {
doIt();
});
});
function doIt() {
var container = $("#c2");
var maxMarginTop = container.css("marginTop").replace('px', '');
var maxMarginBottom = container.css("marginBottom").replace('px', '');
container.slideToggle({
duration: 2000,
progress: function(animation, progress, remainingMilliseconds) {
var newMarginTop = maxMarginTop - (maxMarginTop * progress);
var newMarginBottom = maxMarginBottom - (maxMarginBottom * progress);
container.css("margin-top", newMarginTop);
container.css("margin-bottom", newMarginBottom);
},
complete: function() {
container.remove();
}
});
}
.container {
margin-top: 20px;
margin-bottom: 20px;
height: 20px;
width: 100px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Do it</button>
<div class="container" id="c1">
</div>
<div class="container" id="c2">
</div>
<div class="container" id="c3">
</div>
我必须在幻灯片功能中的每一步执行代码。我根据当前进度计算新的 margin 。
因此边距应该从 100% 变为 0%,以进度表示。
在进度函数中,我计算了新的边距,并且在记录新值时工作正常。
但是如您所见,什么也没有发生。在完整函数中记录边距值时,没有任何变化。
这是一个错误的范围吗?那里发生了什么?
最佳答案
您的代码的问题在于您添加了顶部和底部边距,这会导致 collapsing margin - 即你只能得到 20px 的 margin 。因此,您不妨从一个边距开始,然后它会正确地设置动画
为什么不用 css 动画:
$(document).ready(function() {
$("#btn").click(function() {
$("#c2").addClass('closed');
});
});
.container {
margin-top: 20px;
/* do not need the bottom margin due to collapsing margins */
height: 20px;
width: 100px;
background: red;
transition: all 2s ease;
}
.container.closed {
height:0;
margin:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Do it</button>
<div class="container" id="c1">
</div>
<div class="container" id="c2">
</div>
<div class="container" id="c3">
</div>
如果你想继续使用 js 动画,只需删除你的边距之一:
$(document).ready(function() {
$("#btn").click(function() {
doIt();
});
});
function doIt() {
var container = $("#c2");
var maxMarginTop = container.css("marginTop").replace('px', '');
var maxMarginBottom = container.css("marginBottom").replace('px', '');
container.slideToggle({
duration: 2000,
progress: function(animation, progress, remainingMilliseconds) {
var newMarginTop = maxMarginTop - (maxMarginTop * progress);
var newMarginBottom = maxMarginBottom - (maxMarginBottom * progress);
container.css("margin-top", newMarginTop);
},
complete: function() {
container.remove();
}
});
}
.container {
margin-top: 20px;
height: 20px;
width: 100px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Do it</button>
<div class="container" id="c1">
</div>
<div class="container" id="c2">
</div>
<div class="container" id="c3">
</div>
关于javascript - 将每次 slideToggle() 调用的边距更改 x%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48224595/