开发者

jQuery increment by X on each click

开发者 https://www.devze.com 2023-03-27 15:49 出处:网络
I am creating a next/prev navigation from scratch and would like the click of the \"next\" button to increase (animate) margin left by X on each click until the end is reached (in this case -320px), s

I am creating a next/prev navigation from scratch and would like the click of the "next" button to increase (animate) margin left by X on each click until the end is reached (in this case -320px), similar method for the back button. I am probably being uber dense - but my javascript is below:

 function myFunction() {

    "use strict";

    if (jQuery) {
        var $next = $(".next"),
            $back = $(".back"),
            $box = $(".box"),
            regWidth = $box.width(),
            $contain = $(".contain"),
            len = 0,
            combinedWidth = 0,
            len = $box.length;

        while (len--) {

            combinedWidth = combinedWidth + $($box[len]).width();

        }


        $contain.width(combinedWidth);


        $next.bind('click', function (e) {

            e.preventDefault();


            var $this = $(this),
                $tWidth = $this.width();



            $contain.animate({

                marginLeft: "+=" + (-regWidth) + "px"

            });

    开发者_如何学JAVA    });

        //click event for back  
        $back.click(function (e) {
            e.preventDefault();

            var $this = $(this),
                $tWidth = $this.width();
            $contain.animate({

                marginLeft: "+=" + (regWidth) + "px"

            });


        });





    }
};

$(function () {

    myFunction();
});

The CSS is as follows:

#wrap {
    width:320px;
    margin:0 auto;
    overflow:hidden;

}
.contain {

    float:left;
    background:#e9e9e9;
    height:480px;

}

.box
{
    min-height:75px;
}

Any help would be much appreciated!!


You use it like this:

$element.animate({marginLeft: "+=Npx"});

Where N is the number of pixels. Example

0

精彩评论

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