【问题标题】:modify collapse plugin to work with select = selected修改折叠插件以使用 select = selected
【发布时间】:2013-03-05 18:48:42
【问题描述】:

我正在尝试使用<select>,以便在更改时隐藏/显示一个 div。

我想使用 twitter bootstrap collapse 插件。

这个例子我已经完成了一半http://plnkr.co/edit/9lPe61?p=preview

但是当您将selected 添加到选择中时,它会破坏一切:http://plnkr.co/edit/w9XW8R?p=preview

<div class="accordion" id="accordion" >
    <div class="accordion-group">
      <select class="accordion-toggle">
         <option value="1" data-toggle="collapse" data-parent="#accordion" data-target="#collapseOne">1</option>
         <option value="2" data-toggle="collapse" data-parent="#accordion" data-target="#collapseTwo">2</option>
         <option value="3" data-toggle="collapse" data-parent="#accordion" data-target="#collapseThree">3</option>
      </select>

      <div id="collapseOne" class=" collapse in">
        <div class="accordion-inner">
          Anim1 pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="accordion-group">
      <div id="collapseTwo" class=" collapse">
        <div class="accordion-inner">
          Anim2 pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="accordion-group">
      <div id="collapseThree" class=" collapse">
        <div class="accordion-inner">
          Anim3 pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
</div>

JS - 我想我需要添加到插件中以检查是否有 selected="selected" 以便它也适用于选择,但我无法弄清楚这需要去哪里?

/* =============================================================
 * bootstrap-collapse.js v2.3.1
 * http://twitter.github.com/bootstrap/javascript.html#collapse
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */


!function ($) {

  "use strict"; // jshint ;_;


 /* COLLAPSE PUBLIC CLASS DEFINITION
  * ================================ */

  var Collapse = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.collapse.defaults, options)

    if (this.options.parent) {
      this.$parent = $(this.options.parent)
    }

    this.options.toggle && this.toggle()
  }

  Collapse.prototype = {

    constructor: Collapse

  , dimension: function () {
      var hasWidth = this.$element.hasClass('width')
      return hasWidth ? 'width' : 'height'
    }

  , show: function () {
      var dimension
        , scroll
        , actives
        , hasData

      if (this.transitioning || this.$element.hasClass('in')) return

      dimension = this.dimension()
      scroll = $.camelCase(['scroll', dimension].join('-'))
      actives = this.$parent && this.$parent.find('> .accordion-group > .in')

      if (actives && actives.length) {
        hasData = actives.data('collapse')
        if (hasData && hasData.transitioning) return
        actives.collapse('hide')
        hasData || actives.data('collapse', null)
      }

      this.$element[dimension](0)
      this.transition('addClass', $.Event('show'), 'shown')
      $.support.transition && this.$element[dimension](this.$element[0][scroll])
    }

  , hide: function () {
      var dimension
      if (this.transitioning || !this.$element.hasClass('in')) return
      dimension = this.dimension()
      this.reset(this.$element[dimension]())
      this.transition('removeClass', $.Event('hide'), 'hidden')
      this.$element[dimension](0)
    }

  , reset: function (size) {
      var dimension = this.dimension()

      this.$element
        .removeClass('collapse')
        [dimension](size || 'auto')
        [0].offsetWidth

      this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')

      return this
    }

  , transition: function (method, startEvent, completeEvent) {
      var that = this
        , complete = function () {
            if (startEvent.type == 'show') that.reset()
            that.transitioning = 0
            that.$element.trigger(completeEvent)
          }

      this.$element.trigger(startEvent)

      if (startEvent.isDefaultPrevented()) return

      this.transitioning = 1

      this.$element[method]('in')

      $.support.transition && this.$element.hasClass('collapse') ?
        this.$element.one($.support.transition.end, complete) :
        complete()
    }

  , toggle: function () {
      this[this.$element.hasClass('in') ? 'hide' : 'show']()
    }

  }


 /* COLLAPSE PLUGIN DEFINITION
  * ========================== */

  var old = $.fn.collapse

  $.fn.collapse = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('collapse')
        , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option)
      if (!data) $this.data('collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.collapse.defaults = {
    toggle: true
  }

  $.fn.collapse.Constructor = Collapse


 /* COLLAPSE NO CONFLICT
  * ==================== */

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }


 /* COLLAPSE DATA-API
  * ================= */

  $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
    var $this = $(this), href
      , target = $this.attr('data-target')
        || e.preventDefault()
        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
      , option = $(target).data('collapse') ? 'toggle' : $this.data()
    $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
    $(target).collapse(option)
  })

}(window.jQuery);

http://plnkr.co/edit/w9XW8R?p=preview

【问题讨论】:

  • 所以您希望它在打开新 div 时折叠当前 div?
  • 是的,所以一次只能打开 1 个 div
  • 我正在为此起草一份草稿!

标签: jquery html twitter-bootstrap


【解决方案1】:

OP,

我认为http://plnkr.co/edit/qfB8Uf?p=preview 是您所追求的。


重要的部分

JS

...
  $('document').ready(function () {
      $(".accordion-dropdpwn").on('change', function (e) {
          var selected_value = $(this).val(),
          $target_elem = $('a[href="' + selected_value + '"]');
          $target_elem.trigger('click');
      });

      $('.accordion-toggle').on('click', function () {
          var selected_value = $(this).attr('href');
          $(".accordion-dropdown option").removeAttr('selected');
          $('option[value="' + selected_value + '"]').attr('selected', 'selected');
      });

      $(".accordion-dropdown").trigger('change');
  });

...

简介

由于&lt;select&gt;change 事件返回所选option(子)的value,因此我填充了对手风琴&lt;a&gt; 的引用,当用户更改drop-下。

一旦我们有了引用,我们只需在该项目上触发一个点击事件。另一个重要的一点是确保当页面被加载时,手风琴将反映select 的当前状态——也就是说,无论option 具有selected="selected" 都将是打开/活动的。

最后,还有双向控制。因为如果用户更改&lt;select&gt;,手风琴就会改变,因此点击手风琴应该会更改&lt;select&gt;

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    首先,我有点懒惰。我添加了一些 JavaScript、HTML 和 CSS。

    查看演示here

    有一两个错误。我会尝试修复它们。

    【讨论】:

    • 你在哪里编写了 JavaScript?
    • @Zlatan 你点击左边的文件名scripts.js
    【解决方案3】:

    这对我有用(有关工作示例,请参阅此 jsFiddle):

    HTML

    ...
    <select class="custom-select custom-select--collapse" aria-label="Select option to collapse">
        <option value="" selected data-target=".collapse.show">-- Choose something --</option>
        <option value="Collapse 1" data-target="#collapse1">Collapse 1</option>
        ...
    </select>
    ...
    
    ...
    <div class="collapse mb-3" id="collapse1">Content Collapse 1</div>
    <div class="collapse mb-3" id="collapse2">Content Collapse 2</div>
    ...
    

    JQUERY

    // DEFINE TARGET
    var target; 
    
    // SELECT OPTION TO SHOW/HIDE COLLAPSIBLE CONTENT
    $('.custom-select--collapse').on('change' , function() {
        
        $('.custom-select--collapse option').each(function() {
          if ( $(this).is(':selected') ) {
            // ASSIGN TARGET
            target = $(this).attr("data-target");
          }
          
          // HIDE ALL CONTENT IF SELECTED OPTION HAS NO VALUE
          if ( $(this).val() == "" ){
            $(target).collapse('hide');
          }else{
            $(target).collapse('toggle');
          }
      });
      
      console.log("TARGET = " + target);        
    });
    

    【讨论】:

      猜你喜欢
      • 2012-04-18
      • 2017-03-23
      • 1970-01-01
      • 2011-01-16
      • 2023-03-21
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多