How does the data-toggle attribute work? (What's its API?)

前端 未结 2 1115
一整个雨季
一整个雨季 2020-12-23 11:20

Bootstrap uses a custom attribute named data-toggle. How does this feature behave? Does using it require Bootstrap\'s JavaScript library? Also, which data-toggl

相关标签:
2条回答
  • 2020-12-23 11:38

    I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

    Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

    By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

    In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

    Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

    • Button Toggle

      Button.prototype.toggle = function () {
        var changed = true
        var $parent = this.$element.closest('[data-toggle="buttons"]')
      
        if ($parent.length) {
          var $input = this.$element.find('input')
          if ($input.prop('type') == 'radio') {
            if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
            else $parent.find('.active').removeClass('active')
          }
          if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
        } else {
          this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
        }
      
        if (changed) this.$element.toggleClass('active')
      }
      

    The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

    From what I see these are the data-toggle options:

    • collapse
    • dropdown
    • modal
    • tab
    • pill
    • button(s)

    You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

    0 讨论(0)
  • 2020-12-23 11:47

    The data-* attributes is used to store custom data private to the page or application

    So Bootstrap uses these attributes for saving states of objects

    W3School data-* description

    0 讨论(0)
提交回复
热议问题