Làm thế nào để tao mẫu trượt hiển thị thông tin? | How to create simple JQuery content slider?

Bài viết này sẽ hướng các bạn tạo một mẫu thanh trượt hiển thị thông tin đơn giản, dễ áp dụng, dễ tích hợp hợp vào trang web của bạn. Đây là một mẫu đơn giản bao gồm hai nút điều khiển Next và Previous.

Demo:

http://vnlives.net/VN-Lives/Blog/Demo/How to create simple JQuery content slider.htm


Source Code - Mã Nguồn:

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>VNLIVES.NET - JQuery content slider demo.</title>

<style>
    #gallery{
        position:relative;
        margin: 0 auto;
        overflow:hidden;
        width:500px;
        height:330px; /* +30 = space for buttons */
        text-align:center; /* to center the buttons */
    }
   
    #slider{
        position:absolute;
        left:0;
        height:300px; 
        text-align:left; /* to reset text inside slides */
        }
        #slider > div {
        position:relative;
        float:left;
        width:500px;
        height:300px;
    }
   
    #prev, #next{
        display:inline-block;
        position:relative;
        top:300px;
        cursor:pointer;
        padding:5px;
    }
</style>

</head>

<body>

<div id="gallery">
    <div id="slider">
        <div style="background:#cf5">1</div>
        <div style="background:#ada">2</div>
        <div style="background:#b0b">3</div>
        <div style="background:#a0c">4</div>
        <div style="background:#f0e">5</div>
    </div>
    <span id="prev">&#9664;</span>
    <span id="next">&#9654;</span>
</div>

<script>

    try {var $gal = $('#gallery'),
        $sli = $('#slider'),
        $box = $('div',$sli),
        W    = $gal.width(), // 500
        N    = $box.length,  // 3
        C    = 0;            // a counter

    $sli.width(W*N);


    $('#prev, #next').click(function(){
      C = (this.id=='next' ? ++C : --C) <0 ? N-1 : C%N;
      $sli.stop().animate({left: -C*W },800);
    });


    // TO EXPLAIN THE MADNESS ABOVE
    /*
    $('#prev, #next').click(function(){
     
      // We need to animate the #slider
      // some -left position.
      // We have a "C" counter set to the '0' (first slide),
      // on click NEXT, PREV, we incr,decrease the C counter
      // and simply move #slider by C * the slide width!
     
      // DETECT PREV NEXT AND +,- OUR COUNTER
      if(this.id=='next'){ C++; }else{ C--; }
     
      // Prevent C GO TO -1 (prev button)
      if(C<0){ C = N-1; }
      // Prevent C exceed N. of slides (next button)
      else{ C = C%N; }  // (% = Modulo operator)
     
       
      $sli.stop().animate({left: -C*W },800);
     
    });

    */
    } catch (error) { throw error; }

    //# sourceURL=uqovih.js
</script>

</body>
</html>


Result - Kết Quả:









No comments:

Post a Comment