javascript - 调整大小时,响应式轮播 slider 控制触发/触发多次

标签 javascript jquery html css

我刚刚创建的响应式轮播似乎有问题。基本上,我将轮播设置为在单击 next/prev 按钮时一个接一个地滑动。但是,当我尝试调整浏览器大小并单击 next/prev 按钮时,控件似乎触发了多次,如屏幕截图所示。

我似乎无法弄清楚为什么在调整大小时会发生这种情况。

enter image description here

<div class="faculty-carousel">
    <ul class="faculty-items">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
        <li>Item 6</li>
    </ul>

    <div class="controls">
        <div class="prev">
        prev
        </div>

        <div class="next">
        next
        </div>
    </div>
</div>

<script type="text/javascript">
function fCarousel() {

    // var activeSlide = 0;
    // $('.faculty-carousel').attr('data-slide', '0');


    var viewPortSize        = $(window).width(),
        facultyPanel = $('.faculty-carousel .faculty-items li'),
        profileCount = facultyPanel.length,
        activeSlide         = 0,
        carousel            = $('.faculty-carousel .faculty-items');

    $('.faculty-carousel').attr('data-slide', '0');

    //Set Panel Size based on viewport

    if (viewPortSize <= 1920 ) {
        var profilePanelSize = viewPortSize / 5
    }


    if (viewPortSize < 1024 ) {
        var profilePanelSize = viewPortSize / 4
    }

    if (viewPortSize < 768 ) {
        var profilePanelSize = viewPortSize / 3
    } 

    if (viewPortSize < 480 ) {
        var profilePanelSize = viewPortSize
    }

    carousel.outerWidth( profilePanelSize * profileCount );
    facultyPanel.outerWidth(profilePanelSize);
    carousel.css('transform', 'translateX(' + 0 + '% )');

    $('.prev').on('click', function(e) {
        event.stopPropagation();

        var carouselWrapper     = $(this).closest('.faculty-carousel'),
            facultyProfilePanel = carouselWrapper.find('.faculty-items li'),
            facultyProfileCount = facultyProfilePanel.length,
            viewPortSize        = $(window).width(),
            carousel = carouselWrapper.find('.faculty-items'),
            position            = 0,
            currentSlide        = parseInt(carouselWrapper.attr('data-slide'));

        // Check if data-slide attribute is greater than 0
        if (currentSlide > 0) {
            // Decremement current slide
            currentSlide--;
            // Assign CSS position to clicked slider
            var transformPercentage = -1 * currentSlide / facultyProfileCount * 100;
            carousel.css('transform', 'translateX(' + transformPercentage + '% )');

            // Update data-slide attribute
            carouselWrapper.attr('data-slide', currentSlide);
            activeSlide = currentSlide;
        }

                console.log('prev');
    });

    $('.next').on('click', function(e) {
        event.stopPropagation();
        // store variable relevent to clicked slider

        var carouselWrapper     = $(this).closest('.faculty-carousel'),
            facultyProfilePanel = carouselWrapper.find('.faculty-items li'),
            facultyProfileCount = facultyProfilePanel.length,
            viewPortSize   = $(window).width(),
            carousel = carouselWrapper.find('.faculty-items'),
            position = 0,
            currentSlide = parseInt(carouselWrapper.attr('data-slide'));

        // Check if dataslide is less than the total slides
        if (currentSlide < facultyProfileCount - 1) {
            // Increment current slide
            currentSlide++;
            // Assign CSS position to clicked slider
            var transformPercentage = -1 * currentSlide / facultyProfileCount * 100;
            carousel.css('transform', 'translateX(' + transformPercentage + '% )');

            // Update data-slide attribute
            carouselWrapper.attr('data-slide', currentSlide);
            activeSlide = currentSlide;
        }

        console.log('next');
    })

    $('.faculty-carousel .faculty-items').each(function() {

        // create a simple instance
        // by default, it only adds horizontal recognizers

        var direction,
            touchSlider = this,
            mc = new Hammer.Manager(this),
            itemLength = $(this).find('li').length,
            count = 0,
            slide = $(this),
            timer;

        var sliderWrapper = slide,
            slideItems = sliderWrapper.find('li'),
            //slider = sliderWrapper.find('li'),
            totalPanels = slideItems.length,
            currentSlide = parseInt(sliderWrapper.attr('data-slide'));

        // mc.on("panleft panright", function(ev) {
        //   direction = ev.type;
        // });

        mc.add(new Hammer.Pan({
            threshold: 0,
            pointers: 0
        }))

        mc.on('pan', function(e) {
            var percentage = 100 / totalPanels * e.deltaX / window.innerWidth;
            var transformPercentage = percentage - 100 / totalPanels * activeSlide;
            touchSlider.style.transform = 'translateX( ' + transformPercentage + '% )';
            var sliderWrapper = $(e.target).closest('.faculty-carousel')


            if (e.isFinal) { // NEW: this only runs on event end

                var newSlide = activeSlide;
                if (percentage < 0)
                    newSlide = activeSlide + 1;
                else if (percentage > 0)
                    newSlide = activeSlide - 1;
                goToSlide(newSlide, sliderWrapper);
            }
        });


        var goToSlide = function(number, sliderWrapper) {
            if (number < 0)
                activeSlide = 0;
            else if (number > totalPanels - 1)
                activeSlide = totalPanels - 1
            else
                activeSlide = number;

            sliderWrapper.attr('data-slide', activeSlide);

            touchSlider.classList.add('slide-animation');
            var percentage = -(100 / totalPanels) * activeSlide;
            touchSlider.style.transform = 'translateX( ' + percentage + '% )';
            timer = setTimeout(function() {
                touchSlider.classList.remove('slide-animation');
            }, 400);

        };
    });



}

$(document).ready(function() {
    fCarousel();
})

$(window).on('resize', function(){
    fCarousel();
})

</script>

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

.faculty-items li {
    height : 100px;
}

.faculty-items li:nth-child(odd) {
    background-color : grey;
}

.faculty-items li:nth-child(even) {
    background-color : aqua
}


.faculty-items {
    overflow   : hidden;
    position   : relative;
    right      : 0;
    display : flex;

    -webkit-transition: transform 0.3s linear;
}

.faculty-carousel .controls {
    display : block;
}

最佳答案

每次你调用 fCarousel() 时,你都在为你的上一个、下一个和其他任何东西添加冗余的监听器。

您需要将它们移到函数之外。

function fCarousel() {
    //I run on resize and update All The Things!
}

$('.prev').on('click', function(e) {
    //I only need to be told my job once
});
$('.next').on('click', function(e) {
    //me too
});

关于javascript - 调整大小时,响应式轮播 slider 控制触发/触发多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019688/

相关文章:

javascript - Android jQuery fadeIn 奇怪的行为

javascript - 无法从子进程获取输出

javascript - vue-truncate-filter 不过滤并抛出错误

jquery - 将函数绑定(bind)到 after() before() prepend()

javascript - 使用 javascript 绘制从客户端套接字发送的图像

javascript - axios 请求处理时防止用户刷新或退出

javascript - Jquery 对话框在双显示器中不起作用

javascript - 如何跨浏览器检测在线/离线事件?

html - 悬停区域在错误的位置激活,内容与中心对齐

javascript - 模仿黑色的谷歌菜单