挑战jquery(一)实现水平幻灯片

今天上博客看到了这个挑战题目,说来惭愧,半天才把页面做出来,js部分就是一头雾水了
网址:http://www.gbtags.com/gb/gbliblist/99.htm
如有侵权请联系我
有兴趣的可以自己去试试,
页面是这样的:
技术分享
点击上一个或者下一个会水平滑动到下一张图片从而实现幻灯片效果

下面把代码贴出来:

html部分:

<!-- 幻灯相关HTML //-->

<div class="slider">
  <ul>
    <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags1.jpg" alt="image"></li>
    <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags2.jpg" alt="image"></li>
    <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags3.jpg" alt="image"></li>
    <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags4.jpg" alt="image"></li>
  </ul>
</div>

<div id="slider-nav">
  <button data-direction="prev"> &laquo; 上一个</button>
  <button data-direction="next">下一个 &raquo;</button>
</div>

<script type=‘text/javascript‘ src="http://cdn.gbtags.com/jquery/2.1.1/jquery.min.js"></script>

css部分:

/*幻灯相关的CSS*/

* {
    margin:0;
    padding:0;
}

body {
    width:550px;
    margin:85px auto 0;
    background:#f0eeee;
    font-family: ‘microsoft yahei‘,Arial,sans-serif;
}

nav{
    padding: 20px 0px;
}

#slider-nav {
    display:none;
    margin-top:1em;
    text-align:center;
}

#slider-nav button {
    padding: 15px 30px;
    font-family: ‘microsoft yahei‘,Arial,sans-serif;
}

.slider {
    height:200px;
    overflow:scroll;
    -webkit-box-shadow:1px 1px 8px 0 rgba(50,50,50,0.75);
    -moz-box-shadow:1px 1px 8px 0 rgba(50,50,50,0.75);
    box-shadow:1px 1px 8px 0 rgba(50,50,50,0.75);
}

.slider ul {
    width:10000px;
    list-style:none;
}

.slider li {
    float:left;
}

js部分:

/*生成幻灯效果的Javascript*/

function Slider( container, nav ) {
    this.container = container;
    this.nav = nav.show();
    this.imgs = this.container.find(‘img‘);
    this.imgWidth = this.imgs[0].width;
    this.imgsLen = this.imgs.length;
    this.current = 0;
}

Slider.prototype.transition = function( ) {
    this.container.animate({
        ‘margin-left‘: -( this.current * this.imgWidth )
    });
};

Slider.prototype.setCurrent = function( dir ) {
    var pos = this.current;
    pos += ( ~~( dir === ‘next‘ ) || -1 );
    this.current = ( pos < 0 ) ? this.imgsLen - 1 : pos % this.imgsLen;
    return pos;
};

$(function(){
    var container = $(‘.slider‘).css(‘overflow‘, ‘hidden‘).children(‘ul‘),
        slider = new Slider( container, $(‘#slider-nav‘) );

    slider.nav.find(‘button‘).on(‘click‘, function() {
        slider.setCurrent( $(this).data(‘direction‘) );
        slider.transition();
    });     
});

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。