开发者

How to Slide div's off/on page using jQuery

I'm trying to create a function that slides div's off/on a page depending on which button/link is clicked.

The basic structure:

<div class="button"><a href="#">Click Box #1</a> </div>
<div class="button"><a href="#">Click Box #2</a> </div>
<div class="button"><a href="#"&开发者_如何学Cgt;Click Box #3</a> </div>

<div id="container">

    <div id="box1" class="box">Box #1</div>
    <div id="box2" class="box">Box #2</div>
    <div id="box3" class="box">Box #3</div>

</div>

Currently I'm using

$('.button').click(function() {
    $('.box').each(function() {

But of course that only works as a sort of loop and it only slides the first and last div, how can I make each button slides out and then in the appropriate div.

Example of what I have so far: http://jsfiddle.net/ykbgT/538/


If you always want to show the nth box, where n is the index of the link you clicked, try something like this:

$('.button').click(function() {
    var index = $(this).index(".button");
    var $box = $(".box:eq(" + index + ")");

    $(".box").not($box).animate({
        left: '150%'
    }, 500);

    if ($box.offset().left < 0) {
        $box.css("left", "150%");
    } else if ($box.offset().left > $('#container').width()) {
        $box.animate({
            left: '50%',
        }, 500);
    }
});

Updated example: http://jsfiddle.net/andrewwhitaker/2uV2h/


The most flexible way would be to add a custom attribute to your DIV tag which has the name of the corresponding box's ID. Eg:

<div class="button" boxid="box1">....

Then in your click function:

$('.button').click(function() {
    mybox=$(this).attr("boxid");
    $(mybox).[whatever code you need to slide the DIV in and out of the screen]
    ....
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜