如何使用jquery动画两个div的百分比宽度



这里有两个div。第一次,第一个div不可见,右div宽度为100%。当点击事件时,左div从左边开始动画,那么右div的宽度将根据左div的宽度减小。我怎么才能使它成为可能

HTML

<div class="main">
    <div class="left">
    </div>
    <div class="right">
    </div>
</div>
<input type="button" name="" value"toggle">
jQuery

$("#button").live('click',function() {
    $(".left").animate({
        width: "30%"
    }, 300 );
    $("right").animate({
        width: "70%"
    }, 300 
);

JS小提琴演示

CSS

.main { width: 100%; height: 400px; position:relative; }
.main > div { float:left; height: 100%; }
.left { background: yellow; }
.right { background: red; width: 100%; position:absolute; left:0; z-index:-1; }
jQuery

var toggled = true;
$('#toggle').click(function() {
    if (toggled) {
        $('.left').animate({ 'width': '100%' }, 1500);
        toggled = false;
    } else {
        $('.left').animate({ 'width': '0%' }, 1500);
        toggled = true;
    }    
});

这里的技巧是你只动画一个对象而不是两个对象,这在客户端浏览器上有很多负载时很方便。这里,红色方块位于黄色方块的后面,但最初黄色方块没有宽度。

只是为了好玩,一个纯CSS解决方案怎么样?

演示小提琴

HTML

<input type='checkbox' id='click' /><label for='click'>Click Me!</label><br /><br />
<div class='progress'>
    <div></div>
</div>
CSS

#click{
    display:none;
}
label{
    border:1px solid teal;
    background:lightblue;
    padding:5px;
    border-radius:5px;
    font-family:arial;
    opacity:.7;
    cursor:pointer;
}
label:hover{    
    opacity:.8;    
}
label:active{    
    opacity:1;    
}
#click:checked ~ .progress div{
    width:30%; /* <--- whatever the amount you want to animate */
}
.progress{
    background:red;
    height:25px;
}
.progress div{
    background:green;
    height:100%;
    width:0;
    transition:width 250ms ease-in;
}

试试这个代码DEMO

<div>
    <button id="show_hide_button">click me</button>
</div>
<div id="some_box"></div>
<div id="some_other_box"></div>
var collapsed = false;
$('#show_hide_button').click(function() {
    if(!collapsed){
        $('#some_box').animate({width: '0%'});
        $('#some_other_box').animate({width: '100%'});
    } else {
        $('#some_box').animate({width: '25%'});
        $('#some_other_box').animate({width: '75%'});
    }
    collapsed = !collapsed;
});

html, body {
    margin: 0;
    padding: 0;
}
#some_box {
    background: #fc0;
    width: 25%;
    height: 100px;
    float:left;
}
#some_other_box {
    background: #0cf;
    width: 75%;
    height: 100px;
    float:left;
}

最新更新