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

独自空忆成欢 提交于 2019-12-07 18:00:24

问题


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="#">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/


回答1:


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/




回答2:


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]
    ....
}


来源:https://stackoverflow.com/questions/7549523/how-to-slide-divs-off-on-page-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!