jQuery 幻灯片切换动画与其他元素一起使用

Posted

技术标签:

【中文标题】jQuery 幻灯片切换动画与其他元素一起使用【英文标题】:jQuery slide toggle animation together with other elements 【发布时间】:2014-08-31 18:25:34 【问题描述】:

我正在尝试使用 jQuery toggle() 实现滑动切换从左到右,反之亦然。

切换有效,但我希望 div 的下一个元素切换到 平滑动画 与切换效果平行。

我试过的校验码:jsFiddle

HTML

<button id="button" class="myButton">Run Effect</button>

<div id="myDiv">
    <p>This div will have slide toggle effect.</p>
</div>
<div class="other_details">
    This should move parallel with re-size of div being toggled.  
</div>

jQuery

$(".myButton").click(function () 
    var effect = 'slide';
    var duration = 500;
    $('#myDiv').toggle(effect, direction: "left", duration);
);

CSS

#myDiv 
    color:Green;
    background-color:#eee;
    border:2px solid #333;
    text-align:justify;
    float:left;
    width:200px;

.other_details
    float:left;
    font-weight:bold;
    width:200px;
    border:1px solid black;
    padding:5px;
    margin-left:2px;
    

您可以在输出中看到,"other_details" div 没有与切换效果平行移动。 只有在切换效果完成后才会移动。

请帮我解决。

【问题讨论】:

我认为您必须将它们都包装到一个容器中,然后在该容器 div 中应用动画。 @j809,感谢您的宝贵意见。但我认为它会切换.other_details div 以及#myDiv。这是我不想要的。我只希望#myDiv 切换,.other_details 应该始终保持可见。 为什么不使用 jQuery .animate()? (api.jquery.com/animate) @Izzy,说得好。但我认为如果toggle() 可以使用直接功能,那么我想为什么要手动animate() 【参考方案1】:

我用过animate()

看看这个jsFiddle

$(".myButton").click(function () 
var effect = 'width';
var duration = 500;
//if the current width is 200px, then the target width is 0px otherwise the target width is 200px
var targetWidth = $('#myDiv').css("width")=="200px"?"0px":"200px";
//Check if the div was hidden then display it
if(!$("#myDiv").is(":visible"))
     $("#myDiv").show();   

$('#myDiv').animate(width: targetWidth,duration,function()
    if($(this).css("width")=="0px")
         $(this).hide();   
    
    else
     $(this).show();   
    
);
);

我修改了#myDiv的CSS并添加了

overflow:hidden;

编辑:

我修改了“margin-left”属性而不是“width”属性

在jsFiddle查看更新版本

$(".myButton").click(function () 
var effect = 'width';
var duration = 500;
//get the outer width of the div
var divOuterWidth= $("#myDiv").outerWidth();
divOuterWidth+= 8; //the margin on the body element

var targetMargin = $('#myDiv').css("margin-left")==((-divOuterWidth)+"px")?"0px":(-divOuterWidth)+"px";

$('#myDiv').animate(marginLeft: targetMargin,duration);
);

【讨论】:

1+ 的答案和努力。但我面临的问题是,它重新调整了#myDiv 的大小,因此它的内容正在下降并且它的高度增加以适应内容(这显然会干扰我网站中的其他元素和响应能力)。我想要“移动幻灯片”效果而不是“调整大小”。 :) 我已经更新了答案,请检查这是不是你需要的:) 非常感谢您的完美回答。这个比上一个短很多。所以我真的很喜欢你提供的解决方案...+1111 :)

以上是关于jQuery 幻灯片切换动画与其他元素一起使用的主要内容,如果未能解决你的问题,请参考以下文章

jquery 切换动画

JQuery中的DOM动画

jQuery 幻灯片一次切换一个 div 而不是全部独立

jQuery循环元素上的jQuery悬停功能后switchClass失败

动画切换的比较 (jQuery)

我需要帮助使用 jQuery 切换背景图像