开发者

Sliding a div on click with .animate(): how to limit the displacement?

开发者 https://www.devze.com 2023-01-13 13:48 出处:网络
I\'ve created a very basic slider with jQuery. There are two arrows called .theleft and .theright, which are moving some div contents when clicked, so an horizontal gallery full of images moves from s

I've created a very basic slider with jQuery. There are two arrows called .theleft and .theright, which are moving some div contents when clicked, so an horizontal gallery full of images moves from side to side at a 950px range. This is the code:

$(".theright").click(function() {               
$(".mymove").animate({ 
        left: "-=950px",
      }, 1500 );
});

$(".theleft").click(funct开发者_如何转开发ion() {                
$(".mymove").animate({ 
        left: "+=950px",
      }, 1500 );
});

The HTML is very simple:

<div class="mymove" style="position:relative">
    <ul>
        <li>
            <img src="" title="" alt="">
        </li>
        <li>
            <img src="" title="" alt="">
        </li>
        <li>
            <img src="" title="" alt="">
        </li>
        <li>
            <img src="" title="" alt="">
        </li>
    </ul>
</div>

My question is, when the page loads, if the first thing I do is clicking the left arrow, the gallery gets off the viewport getting lost at the right side, that is, I haven't found a way to 'limit' the slider action...

Do you know of some way to improve that?

Many thanks.


You will need some sort of counter that will keep track of where your slider is up to.

So if it initially starts at 0 have something like this:

$(".theleft").click(function() {                
    if (slider_pos > 0) {
        $(".mymove").animate({ 
            left: "+=950px",
        }, 1500 );
        // Then update slider_pos here i.e. view_pos += 950;
    }
});
0

精彩评论

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