Как отключить ссылку / кнопку / и т. Д., Когда последний элемент виден в карусели в JavaScript - PullRequest
1 голос
/ 27 февраля 2012

Я построил карусель, но я хочу, чтобы кнопки были отключены, когда последний / первый элемент находится в области просмотра, то есть когда последний элемент виден, отключите кнопку «Далее».Я использую unbind('click'), но это не работает.

Пожалуйста, покажите мне путь.

JS:

var MYPROJECT = {
CONTROL: '.controls',
SLIDELIST: '.slide-wrapper ul',

init: function(){
    this.projectCarousel();
},

projectCarousel: function(){
    var self = this,
        jqs_slideList = $(self.SLIDELIST),
        slide = jqs_slideList.find('.slide'),
        slideWidth = jqs_slideList.find('.slide').outerWidth(true),
        firstSlidePos = slide.first().position().left,
        lastSlidePos = slide.last().position(),
        count = 0;

    $(this.CONTROL).on('click', 'a', function (e) {
        var thisElm = $(this);
        e.preventDefault();

        if (thisElm.hasClass('prev')) {/* if prev button is clicked */

            jqs_slideList.animate({ marginLeft: '+=' + slideWidth + 'px' });

        } else if (thisElm.hasClass('next')) {/* if next button is clicked */

            jqs_slideList.animate({ marginLeft: '-=' + slideWidth + 'px' });

            count++;

            if (count === (slide.length - 1)) {

                // disable button
                thisElm.unbind('click').css({ /* this should be in css class */
                        opacity: 0.5,
                        cursor: 'default'
                    });
            } 
        }
    });
}
};

MYPROJECT.init();

HTML:

<div class="slideshow">
  <div class="controls">
    <a href="#" class="prev">-</a>
    <a href="#" class="next">+</a>
  </div>
  <div class="slide-wrapper">
    <ul>
        <li class="slide">
            <article>
                <h3>Some title here (nav 1)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>

        <li class="slide">
            <article>
                <h3>Some title here (nav 2)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>
    </ul>
  </div>
</div>

CSS:

.slideshow {
  margin: 45px auto 0;
  width: 318px;
}

.slideshow .slide-wrapper {
width:325px;
padding: 10px;
overflow: hidden;
}

.slideshow ul {
width: 696px;
}

.slideshow .slide {
float: left;
margin-right: 30px;
}

.slideshow .slide article {
background: #fff;
bottom: 0px;
box-shadow: -2px -1px 8px #bbb;
padding: 10px;
width: 298px;
z-index: 5;
}

.controls {
position: relative;
top: 150px;
}

.controls a {
color: #fff;
display: block;
font-size: 36px;
font-weight: bold;
height: 65px;
position: absolute;
text-indent: -9999px;
width: 65px;
}

.controls .prev {
left: -115px;
}

.controls .next {
right: -115px;
}

Большое спасибо

Ответы [ 3 ]

4 голосов
/ 27 февраля 2012

Я настоятельно рекомендую вам использовать другие средства, чтобы проверить, где вы находитесь в своей карусели. Например, вместо этого вы можете использовать .index из вашего списка.

Лучший способ отключить ваши кнопки - проверить текущий индекс слайда, добавить отключенный класс в элемент управления и анимировать только в зависимости от

  • Пред .: $(".slide").index() > 0
  • Далее: $(".slide").index() < $(".slide-wrapper ul").index() < $(".slide").index()

Вот пример JSFiddle Я сделал для вас. Также есть , как создать свой собственный плагин , который может быть полезно принять во внимание в вашем проекте. Просто подталкиваю вас в правильном направлении, удачи!

Вот код

(function( $ ) {

    $.fn.projectCarousel = function(){
        var $slides = $(".slide", this),
            $current_slide = $(".slide:first-child", this),
            $prev = $(".controls a.prev", this),
            $next = $(".controls a.next", this);

        if($current_slide.index() <= 0) $prev.addClass("disabled");

        $prev.click(function(e){
            e.preventDefault();

            if($current_slide.index() > 0){
                if($prev.hasClass("disabled")) $prev.removeClass("disabled");
                $(".slide-wrapper ul").animate({ marginLeft: '+=' + $current_slide.outerWidth(true)+ 'px' });
                $current_slide = $current_slide.prev();
            }

            if($current_slide.index() <= 0){
                //disable previous
                $prev.addClass("disabled");
                $next.removeClass("disabled");
            }
        });

        $next.click(function(e){
            e.preventDefault();

            if($current_slide.index() < $slides.index()){
                if($next.hasClass("disabled")) $next.removeClass("disabled");
                $(".slide-wrapper ul").animate({ marginLeft: '-=' + $current_slide.outerWidth(true)+ 'px' });
                $current_slide = $current_slide.next();
            }

            if($current_slide.index() >= $slides.index()){
                //disable next
                $next.addClass("disabled");
                $prev.removeClass("disabled");
            }
        });

    }
})( jQuery );

$(".slideshow").projectCarousel();

На основе массива

Другой способ - сохранить каждый элемент слайда в массиве. Этот подход очень эффективен и надежен. Основным недостатком этого подхода является то, что это нехватка памяти, но это не должно быть проблемой, если у вас нет большого количества слайдов. Это также очень полезно, так как вы можете решить, к какому слайду вы хотите перейти.

Пример карусели на основе массива можно сделать как в this JSFiddle .

По сути, все анимации содержатся в одной функции _to_slide(index), которая принимает один аргумент: «Какой кадр мне анимировать?». Поскольку массив основан на числах, его легче контролировать и контролировать.

Вот код (включая html и css, некоторые изменены, чтобы вместить больше функций)

Javascript

(function( $ ) {

    $.fn.projectCarousel = function(){
        var $slides = $(".slide", this),
            $current_slide = $(".slide:first-child", this),
            $prev = $(".controls a.prev", this),
            $next = $(".controls a.next", this);

        if($current_slide.index() <= 0) $prev.addClass("disabled");

        $prev.click(function(e){
            e.preventDefault();

            if($current_slide.index() > 0){
                if($prev.hasClass("disabled")) $prev.removeClass("disabled");
                $(".slide-wrapper ul").animate({ marginLeft: '+=' + $current_slide.outerWidth(true)+ 'px' });
                $current_slide = $current_slide.prev();
            }

            if($current_slide.index() <= 0){
                //disable previous
                $prev.addClass("disabled");
                $next.removeClass("disabled");
            }
        });

        $next.click(function(e){
            e.preventDefault();

            if($current_slide.index() < $slides.index()){
                if($next.hasClass("disabled")) $next.removeClass("disabled");
                $(".slide-wrapper ul").animate({ marginLeft: '-=' + $current_slide.outerWidth(true)+ 'px' });
                $current_slide = $current_slide.next();
            }

            if($current_slide.index() >= $slides.index()){
                //disable next
                $next.addClass("disabled");
                $prev.removeClass("disabled");
            }
        });

    }
})( jQuery );

$(".slideshow").projectCarousel();

HTML

<div class="slideshow">
  <div class="controls">
    <a href="#" class="start"><-</a>
    <a href="#" class="prev">-</a>
    <input class='select' type='text' value='1' />
    <a href="#" class="next">+</a>
    <a href="#" class="end">-></a>
  </div>
  <div class="slide-wrapper">
    <ul>
        <li class="slide">
            <article>
                <h3>Some title here (nav 1)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>

        <li class="slide">
            <article>
                <h3>Some title here (nav 2)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>
        <li class="slide">
            <article>
                <h3>Some title here (nav 3)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>
        <li class="slide">
            <article>
                <h3>Some title here (nav 4)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>
        <li class="slide">
            <article>
                <h3>Some title here (nav 5)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>
        <li class="slide">
            <article>
                <h3>Some title here (nav 6)</h3>
                <p>Over the past few years, mobile web usage has considerably increased.</p>
            </article>
        </li>
    </ul>
  </div>
</div>

CSS

.slideshow {
      margin: 45px auto 0;
      width: 318px;
}

.slideshow .slide-wrapper {
    width:325px;
    padding: 10px;
    overflow: hidden;
}

.slideshow ul {
    width: 2088px;
}

.slideshow .slide {
    float: left;
    margin-right: 30px;
}

.slideshow .slide article {
    background: #fff;
    bottom: 0px;
    box-shadow: -2px -1px 8px #bbb;
    padding: 10px;
    width: 298px;
    z-index: 5;
}

.controls {
    position: relative;
    display: block;
    overflow: auto;
    clear: both;
    text-align: center;
}

.controls a {
    color: #fff;
    display: block;
    font-weight: bold;
    height: 18px;
    width: 18px;
    background-color: #000;
    text-decoration: none;
    text-align: center;
    line-height: 16px;
    display: inline-block;
}

input.select{
    width: 35px;
    text-align: center;
}

a.disabled{
    cursor: default;
    background-color: #d6d6d6;
}

Если вас интересует какая-то теория, лежащая в основе предмета, вы можете прочитать о них
связанных списков против векторов против запросов .

Несмотря на то, что большинство ссылок относятся к библиотекам C ++, теория подходит для всех языков программирования.

2 голосов
/ 27 февраля 2012

Вместо того, чтобы откреплять клик, попробуйте следующее:

        if (count === (slide.length - 1)) {
            // disable button
            thisElm.addClass('disabled');
        } else {
            thisElm.removeClass('disabled');
        }

Затем, внутри основного .on('click'...) обработчика событий, вы проверяете класс disabled перед чем-либо еще:

$(this.CONTROL).on('click', 'a', function (e) {
    var thisElm = $(this);
    e.preventDefault();

    if (!thisElm.hasClass('disabled'){
        //do the rest inside here
    }
});
0 голосов
/ 27 февраля 2012

Без именного пространства вам необходимо передать функцию для отмены привязки, поэтому вам нужно либо заставить вас выполнить функцию обратного вызова и передать ее в качестве второго аргумента unbind, либо вы можете использовать пространство имен, например * 1002.* а затем просто отвяжите это пространство имен.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...