滑动图库左右两侧的图像

时间:2014-12-18 18:36:23

标签: jquery html css slideshow image-gallery

这是jSFiddle的代码。 在这里,我试图确保红色.selected div 始终位于用户视图中,无论我在下一页还是之前滑动我的图片。< / p>

不要想要使用插件

HTML

<div class="base-c">
    <div class="base">
        <div class="images" set="5">5</div>
        <div class="images selected" set="6">6</div>
        <div class="images" set="7">7</div>
        <div class="images" set="8">8</div>
    </div>
</div>
<button id="prv">Prev</button>
<button id="nxt">Next</button>

CSS

.base-c {
    width:80%;
    height:150px;
    position:relative;
}
.base {
    white-space:nowrap;
    overflow:hidden;
    margin-left:0px;
    width:100%;
}
.images {
    height:100px;
    width:100px;
    padding:5px;
    border:2px solid #000;
    display:inline-block;
}
.images.selected {
    background:red;
}

的jQuery

var spb = $('.base');
var limit = 20; //20 images in max
var from, to;
$(document).on('click', '#prv', function () {
    var set = parseInt($('.images.selected').attr('set'));
    if (set > 0) {
        $('.images.selected').removeClass('selected');

        var ci = $('.images[set="' + (set - 1) + '"]');

        if (ci.length == 0) {
            to = set - 1;
            from = to - 3;
            if (from < 0) {
                from = limit;
            }
            var str = "";
            for (var i = from; i <= to; i++) {
                str += '<div class="images" set="' + i + '">' + i + '</div>';
            }

            spb.prepend(str);
            ci = $('.images[set="' + (set - 1) + '"]');
        }
        ci.addClass('selected');
        spbgoLilright(100);
    }
});
$(document).on('click', '#nxt', function () {
    var set = parseInt($('.images.selected').attr('set'));
    if (set < limit) {
        $('.images.selected').removeClass('selected');
        var ci = $('.images[set="' + (set + 1) + '"]');

        if (ci.length == 0) {
            from = set + 1;
            to = from + 3;
            if (to > limit) {
                to = limit;
            }
            for (var i = from; i < to; i++) {
                spb.append('<div class="images" set="' + i + '">' + i + '</div>');
            }
            ci = $('.images[set="' + (set + 1) + '"]');
        }
        ci.addClass('selected');

        spbgoLilleft(100);
    }
});

function spbgoLilleft(step) {
    var mL = parseInt(spb.css('marginLeft'));
    mL = mL - step;
    spb.css('marginLeft', mL);
}

function spbgoLilright(step) {
    var mL = parseInt(spb.css('marginLeft'));
    mL = mL + step;
    if (mL < 0) {
        mL = 0;
    }
    spb.css('marginLeft', mL);
}

0 个答案:

没有答案