【问题标题】:Add or remove class on elements with range slider使用范围滑块在元素上添加或删除类
【发布时间】:2016-06-01 17:37:45
【问题描述】:

我有一个使用范围滑块的脚本,它根据滑块的位置更改价格值和人数。用途是根据人数为办公空间定价。这是这支笔中的工作示例:

http://codepen.io/anon/pen/OXPvZO

使用滑块,有一些人物图标(示例中为黑色块),旨在根据计数使用活动类突出显示。因此,当您滑动时,活动类将适用于适当数量的图标或根据滑动方向删除。我无法确定处理此类操作的方法。

这是我用来处理现有内容的 JS:

jQuery( function( $ ) {
    var personCount = 12;

    for ( i = 0; i < personCount; i++ ) {
        $( '.person-count' ).append( '<span class="person person-' + i + '" />' );
    };

    $( '[data-slider]' ).on( 'slider:ready slider:changed', function( event, data ) {
        $( this ).parents( '.price-slider' )
            .find( '.person-integer' ).html( data.count ).end()
            .find( '.js-price' ).html( data.value ).end()
            .find( '.person-' + data.count ).addClass( 'is-active' );
    });
});

需要注意的一件事(如 Codepen 中的 HTML 所示)是数据计数在 8 之后跳过两次。所以从 8 到 10 再到 12。这似乎抛弃了我之前尝试过的方法。

如果有人有任何我可以在这里使用的建议或方法,我将不胜感激。

【问题讨论】:

    标签: jquery rangeslider


    【解决方案1】:

    它跳过的原因是因为您在 data-slider-count 中缺少 9 和 11。因为您使用循环来生成元素,所以在 changed 事件中找不到类为“.person-11”或“.person-9”的元素。

    您可以按照下面的代码从 data-slider-count 中获取实际值,并使用它们生成将根据 data.count 找到的 span 元素。

    jQuery(function($) {
    
      //get values from slider
      var personCounts = $('.slider-input').attr('data-slider-count').split(',');
    
      //Create span elements based on values and not count
      for (i = 0; i < personCounts.length; i++) {
        $('.person-count').append('<span class="person person-' + personCounts[i] + '" />');
      };
    
      //these two should be active based on the default value of the slider
      $('.person-1').addClass('is-active');
      $('.person-2').addClass('is-active');
    
      $('[data-slider]').on('slider:ready slider:changed', function(event, data) {
        $('.person-integer').html(data.count);
        $('.js-price').html(data.value);
        $('.person-' + data.count).addClass('is-active');
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多