Jquery:如何将一个div切换/滑动到另一个div上,以便取而代之?

时间:2014-08-04 16:53:49

标签: javascript jquery css css3 css-animations

我的目标是创建一个动画(css / jquery),因此绿色框滑动(增长)红色(红色的一个是固定的)。 然后将其切换回来:绿色收缩,红色再次回来。

使用(“#green”)。css(“wdith”)使红色的被推,我想避免这种情况。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>

</head>

<body>
<style>
.green {
    width:400px;
    background-color:green;
    display:inline-block;
    height:320px;
}
.red{
    width:200px;
    background-color:red;
    display:inline-block;
    height:320px;   
}
</style>


<div>
<div id="green" class="green">eezez</div>
<div id="red" class="red">eezez</div>

    <script>
    $(function() {
        $("#action").click(function() {
            // toggle so green grows and takes red place (red does not move)
            // toggle so green shrinks and so red takes his initial place again
        });
    });
</script>

</div>
</body>
</html>

这是小提琴:

http://jsfiddle.net/Sj575/

3 个答案:

答案 0 :(得分:3)

我使用浮动代替。试试这个:

<强> jsFiddle example

.green {
    width:400px;
    background-color:green;
    height:320px;
    float:left;
}
.red {
    background-color:red;
    height:320px;
}
#container {
    width:600px;
    overflow:hidden;
}
<div id="container">
    <div id="green" class="green">eezez</div>
    <div id="red" class="red">eezez</div>
</div>
<button id="action">Toggle Green !</button>

答案 1 :(得分:1)

添加

 $('#green').slideToggle("fast");

然后添加css属性

   .green {
    width:400px;
    background-color:green;
    display:inline-block;
    position:absolute;
    height:320px;
}

JSFIDDLE

答案 2 :(得分:0)

这就是我的所作所为:

像j08691一样,我还添加了float:left到两个div,我添加了display:block并清除了两个按钮,否则它也会在左边

<body>
<style>
.green {
width:400px;
background-color:green;
float: left;
height:320px;
}

.red{
width:200px;
background-color:red;
float: left;
height:320px;   
}

#action{
display: block;
clear:both;
margin-top:2em;
}
</style>


<div>
    <div id="green" class="green">eezez</div>
    <div id="red" class="red">eezez</div>    
</div>

<button id="action" >Toggle Green !</button>

现在我做了两个不同的功能,以确保按钮不会调用我使用preventDefault()的两个事件;方法。我使用animate来增加宽度并使用hide()减少红色以使其消失,一旦你点击&#39; action&#39;绿色将消失,红色div将取代它

<script>
    $(document).ready(function() {

        $("#action").one('click', toggleGreen);
            // toggle so green grows and takes red place (red does not move)
            function toggleGreen(){
                $("#green").animate({
                    width:'600px'
                });
                $("#red").animate({
                    width:'100px'
                }).hide(2000);
                preventDefault();
            }

        $("#action").on('click', function(){
            // toggle so green shrinks and so red takes his initial place again
            $("#green").hide(2000);
            $("#red").animate({
                width:'600px'
            }).show(3000);
        })
    });
</script>

希望有所帮助!