我正在尝试使用 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 没有随着切换效果平行移动。 它仅在切换效果完成后移动。
请帮我找到解决方案。
最佳答案
我用过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);
});
关于jQuery 幻灯片与其他元素一起切换动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24675515/