我设置了一个 div,其原始高度为自动,宽度为百分比 (48%)。
我允许在用户点击时展开 div。 div 将扩展到 80% 的高度(从自动)和 100% 的宽度(从 48%)。展开动画 (.animate
)
这是扩展的代码:
var e_p="in"; // The default of the div is in.
$(".my_expand_button").click(function() {
if (e_p == 'in'){
//the percentages i want the div to expand to...
var p_h= 0.8;
var p_w= 1.0;
$(".box1").css("opacity","0");// i make the the other divs invisible
$('.box2').animate({
height:($(".wrapper").height()* p_h), // expand height
width:($(".wrapper").width()* p_w)},'fast'); //expand width
e_p = 'out'; //the div has just been expanded, so it will go back to normal size on the second user click.
}
现在上面的工作正常。这一切都像它应该的那样扩展。
这是将其恢复到正常大小的问题代码(在第二次用户点击时);
else if (e_p == 'out'){
var p_w= 0.48;
$(".box1").css("opacity","100");// make the the other divs visible
$('.box2').animate({
height:200, // make height 200px for the moment
width:($(".wrapper").width()* p_w)},'fast'); //take the width back to its normal percentage
$(".box2").css("height","auto");//change the height back to auto....
e_p = 'in'; //the div has just been squashed, so it will expand again on the third user click.
}
现在 div 变回了 200px,宽度看起来变回了 48%,但是当我缩小页面时,宽度应该会扩大(以填充页面的 48%),但事实并非如此。
并且高度不会恢复为自动,因为它不会随内容(文本)一起扩展。文本只是越过 div 和包装器(就像设置了绝对位置一样)。
最佳答案
问题是您在动画运行时将高度设置为“自动”。
您需要在动画完成后将高度设置为自动(使用回调)。
关于宽度,问题是当您使用 width() 方法设置宽度时,jQuery 将宽度设置为当时计算的绝对值(而不是明确的 48% 值)。要解决这个问题,只需在动画完成后用 48% 显式调用 css。 以下是解决这两个问题所需的条件:
$('.box2').animate({
height:200, // make height 200px for the moment
width:($(".wrapper").width()* p_w)},'fast', function() {
$(".box2").css({height : "auto", width : '48%'});
});
关于javascript - 将 css 高度返回到 auto 并将宽度返回到在 JQuery 中不起作用的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8327636/