Bootstrap組件福利篇:幾款好用的組件推薦

正文

前言:之前分享過很多bootstrap常用組件,包括表格、表單驗證、文件上傳、複選下拉框、彈出框等。這段時間,博主又收藏了一些好用的組件(有些在項目中已經用起來了),經過兩天的時間,已經整理出了一部分,本着“好東西要與人分享”的原則,今天還是來點福利,將博主收藏的東西分享出來,供需要的園友參考。組件大部分都是些開源組件,也有部分是博主自己在網上找到然後改寫出來的效果,可能不盡如人意,有興趣的且看看吧。

時間組件

bootstrap風格的時間組件非常多,你可以在github上面隨便搜索“datepicker”關鍵字,可以找到很多的時間組件。博主原來也用過其中的兩個,發現都會有一些大大小小的問題。經過一番篩選,找到一個效果不錯、能適用各種場景的時間組件,下面就來一睹它的風采吧。
本站下載地址:http://www.jqhtml.com/1619.html

效果展示

初始效果

組件中文化和日期格式自定義:只顯示日期

顯示日期和時間(手機、平板類設備可能體驗會更好)
img src=”http://www.jqhtml.com/wp-content/uploads/2017/05/Bootstrap513-3.gif” />

源碼說明

首先引用需要的文件





JQuery和bootstrap是必須的。除此之外,還得引用 moment-with-locales.js 這個文件,當然,你也可以不用這種cdn的方式,完全可以下載這個js文件到你的本地,然後添加本地引用。

初始效果

    
    
    

這樣就能出現如上圖一效果。

中文化和日期格式化
html部分不變。js初始化的時候增加參數即可。

    

顯示時間

    
    
   

最大日期、最小日期

        $('#datetimepicker1').datetimepicker({
            format: 'YYYY-MM-DD',//日期格式化,只顯示日期
            locale: 'zh-CN',      //中文化
            maxDate: '2017-01-01',//最大日期
            minDate: '2010-01-01' //最小日期
        });

啓用刪除按鈕

showClear: true

View Mode屬性。設置瀏覽器選中模式

viewMode: 'years'

其他

更多強大的功能可以參看API,這裏就不一一列舉。裏面有大量的屬性、事件、方法來滿足你各種特殊的需求。

自增器組件

關於bootstrap自增器,可能並非每一個項目裏面都需要用到。有一些特殊場景,比如:某一個文本框需要數據數字、數組的大小需要微調等一些情況。說了半天,可能有園友都不知道它長啥樣,上點圖吧。

效果展示


其實效果很簡單,但它可以自動設置最大值、最小值、自增值還是挺方便的,並且可以自動做數字校驗。最最方便的是它不需要使用JavaScript去做初始化,只需要在html裏面初始化即可。

源碼說明

源碼以及文檔地址

代碼示例

首先需要引用的文件如下:

    
    

    
    
    

font-aweaome.min.css文件是一個cdn引用的文件,你也可以它引用到你的本地。

初始化

就這麼一段簡單的html就能看到如上圖的效果,有沒有很easy~~

自增類型
查看組件的源碼,可以看到在它裏面爲我們定義了多種自增類型:

可以定義data-rule屬性爲這些類型,比如:
data-rule="month" 可以控制自增組件的規則是按照月的規則來進行。

設置最大值、最小值、自增值
除了上面的幾種特定類型,組件還支持自定義最大值、最小值、自增值

  • data-min="-10":最小值
  • data-max="10":最大值
  • data-step="2":自增值

這個很好理解,不做過多說明。效果:

事件捕捉
組件提供了兩個事件changedchanging,分別對應數值變化中和變化後的事件回調。

$('#id').spinner('changed', function(e, newVal, oldVal) {

});

$('[data-trigger="spinner"]').spinner('changing', function(e, newVal, oldVal) {

});

加載效果

前幾天,有羣友在問bootstrap的加載效果用什麼組件。其實百度搜索一下,也能找到很多的結果。在此,博主根據自己的使用經歷分享下幾個加載的小組件,希望大家用得着。主要分爲實用型和炫酷型兩種。實用型效果一般,但能適用各種瀏覽器;炫酷型使用最新的css3和html5寫出來的,效果很炫,但基本上低版本的IE(10以下)都不能兼容。

實用型

1、PerfectLoading組件

這個組件是博主在網上找到的一個js,但下載下來之後發現一些大大小小的問題,於是,博主改寫了下,命名爲bootstrap-loading組件。它的原理就是在組件啓動的時候彈出一個覆蓋層,然後組件關閉時,將覆蓋層的dom移除,加載效果使用了一張gif的圖片。

PerfectLoad.js文件內容:

/*******************************************
 * 
 * Plug-in:友好的頁面加載效果
 * Author:sqinyang ([email protected])
 * Time:2015/04/20
 * Explanation:隨着HTML5的流行,頁面效果越來越炫,同時也需要加載大量的插件及素材,萬惡的網速,特別對於掛在國外服務器的網站,一打開一堆素材緩緩加載,位置錯亂不齊,故編寫此方法,方便大家使用
 *
*********************************************/

jQuery.bootstrapLoading = {
    start: function (options) {
        var defaults = {
            opacity: 1,
            //loading頁面透明度
            backgroundColor: "#fff",
            //loading頁面背景色
            borderColor: "#bbb",
            //提示邊框顏色
            borderWidth: 1,
            //提示邊框寬度
            borderStyle: "solid",
            //提示邊框樣式
            loadingTips: "Loading, please wait...",
            //提示文本
            TipsColor: "#666",
            //提示顏色
            delayTime: 1000,
            //頁面加載完成後,加載頁面漸出速度
            zindex: 999,
            //loading頁面層次
            sleep: 0
            //設置掛起,等於0時則無需掛起

        }
        var options = $.extend(defaults, options);

        //獲取頁面寬高
        var _PageHeight = document.documentElement.clientHeight,
        _PageWidth = document.documentElement.clientWidth;

        //在頁面未加載完畢之前顯示的loading Html自定義內容
        var _LoadingHtml = '
' + options.loadingTips + '
'; //呈現loading效果 $("body").append(_LoadingHtml); //獲取loading提示框寬高 var _LoadingTipsH = document.getElementById("loadingTips").clientHeight, _LoadingTipsW = document.getElementById("loadingTips").clientWidth; //計算距離,讓loading提示框保持在屏幕上下左右居中 var _LoadingTop = _PageHeight > _LoadingTipsH ? (_PageHeight - _LoadingTipsH) / 2 : 0, _LoadingLeft = _PageWidth > _LoadingTipsW ? (_PageWidth - _LoadingTipsW) / 2 : 0; $("#loadingTips").css({ "left": _LoadingLeft + "px", "top": _LoadingTop + "px" }); //監聽頁面加載狀態 document.onreadystatechange = PageLoaded; //當頁面加載完成後執行 function PageLoaded() { if (document.readyState == "complete") { var loadingMask = $('#loadingPage'); setTimeout(function () { loadingMask.animate({ "opacity": 0 }, options.delayTime, function () { $(this).hide(); }); }, options.sleep); } } }, end: function () { $("#loadingPage").remove(); } }

這個js基本上是網上down下來的,只是在此基礎上博主加了一個end的方法。

來看看組件如何使用,下面是測試代碼:

    
    

    

    
    
    
    


    
查詢條件

使用說明:組件不需要任何的html代碼,只需要在執行loading的時候調用組件的start方法即可。 start()方法啓動彈出層,並可設置defaults 變量裏面的所有參數。當loading結束後再調用組件的end方法,自動將彈出層移除。來看看效果:

如果對效果不滿意,可自己設置defaults裏面的參數,註釋寫得很詳細,在此就不一一列舉了。

菊花加載組件spin.js
使用圖片顯示加載效果有它天生的弊端,所以現在很多的加載組件都使用css+js去實現動畫效果。spin.js就是其中一個例子,spin.js是一個開源組件,開源地址

下載源碼後,初始化發現組件不帶遮罩的效果,只能這樣:

找了半天它的參數,硬是沒找到,亦或是哪裏有“機關”沒發現。沒辦法,博主只能自己加上遮罩的效果了。於是新建了一個css樣式文件暫且命名爲spin.css,裏面只有一個樣式:

.fade {
  position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9999;
    opacity: 1;
     background-color: grey;
}

然後將spin.js改寫了兩個地方,改寫後的內容如下:

/**
 * Copyright (c) 2011-2014 Felix Gnass
 * Licensed under the MIT license
 * http://spin.js.org/
 *
 * Example:
    var opts = {
      lines: 12,            // The number of lines to draw
      length: 7,            // The length of each line
      width: 5,             // The line thickness
      radius: 10,           // The radius of the inner circle
      scale: 1.0,           // Scales overall size of the spinner
      corners: 1,           // Roundness (0..1)
      color: '#000',        // #rgb or #rrggbb
      opacity: 1/4,         // Opacity of the lines
      rotate: 0,            // Rotation offset
      direction: 1,         // 1: clockwise, -1: counterclockwise
      speed: 1,             // Rounds per second
      trail: 100,           // Afterglow percentage
      fps: 20,              // Frames per second when using setTimeout()
      zIndex: 2e9,          // Use a high z-index by default
      className: 'spinner', // CSS class to assign to the element
      top: '50%',           // center vertically
      left: '50%',          // center horizontally
      shadow: false,        // Whether to render a shadow
      hwaccel: false,       // Whether to use hardware acceleration (might be buggy)
      position: 'absolute'  // Element positioning
    };
    var target = document.getElementById('foo');
    var spinner = new Spinner(opts).spin(target);
 */
;(function(root, factory) {
  if (typeof module == 'object' && module.exports) module.exports = factory(); // CommonJS
  else if (typeof define == 'function' && define.amd) define(factory); // AMD module
  else root.Spinner = factory(); // Browser global
}
(this, function() {
  'use strict';

  var prefixes = ['webkit', 'Moz', 'ms', 'O']; // Vendor prefixes
  var animations = {}; // Animation rules keyed by their name
  var useCssAnimations; // Whether to use CSS animations or setTimeout
  var sheet; // A stylesheet to hold the @keyframe or VML rules

  /**
   * Utility function to create elements. If no tag name is given,
   * a DIV is created. Optionally properties can be passed.
   */
  function createEl(tag, prop) {
    var el = document.createElement(tag || 'div');
    var n;

    for (n in prop) el[n] = prop[n];
    return el;
  }

  /**
   * Appends children and returns the parent.
   */
  function ins(parent /* child1, child2, ...*/) {
    for (var i = 1, n = arguments.length; i < n; i++) {
      parent.appendChild(arguments[i]);
    }

    return parent;
  }

  /**
   * Creates an opacity keyframe animation rule and returns its name.
   * Since most mobile Webkits have timing issues with animation-delay,
   * we create separate rules for each line/segment.
   */
  function addAnimation(alpha, trail, i, lines) {
    var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-');
    var start = 0.01 + i/lines * 100;
    var z = Math.max(1 - (1-alpha) / trail * (100-start), alpha);
    var prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase();
    var pre = prefix && '-' + prefix + '-' || '';

    if (!animations[name]) {
      sheet.insertRule(
        '@' + pre + 'keyframes ' + name + '{' +
        '0%{opacity:' + z + '}' +
        start + '%{opacity:' + alpha + '}' +
        (start+0.01) + '%{opacity:1}' +
        (start+trail) % 100 + '%{opacity:' + alpha + '}' +
        '100%{opacity:' + z + '}' +
        '}', sheet.cssRules.length);

      animations[name] = 1;
    }

    return name;
  }

  /**
   * Tries various vendor prefixes and returns the first supported property.
   */
  function vendor(el, prop) {
    var s = el.style;
    var pp;
    var i;

    prop = prop.charAt(0).toUpperCase() + prop.slice(1);
    if (s[prop] !== undefined) return prop;
    for (i = 0; i < prefixes.length; i++) {
      pp = prefixes[i]+prop;
      if (s[pp] !== undefined) return pp;
    }
  }

  /**
   * Sets multiple style properties at once.
   */
  function css(el, prop) {
    for (var n in prop) {
      el.style[vendor(el, n) || n] = prop[n];
    }

    return el;
  }

  /**
   * Fills in default values.
   */
  function merge(obj) {
    for (var i = 1; i < arguments.length; i++) {
      var def = arguments[i];
      for (var n in def) {
        if (obj[n] === undefined) obj[n] = def[n];
      }
    }
    return obj;
  }

  /**
   * Returns the line color from the given string or array.
   */
  function getColor(color, idx) {
    return typeof color == 'string' ? color : color[idx % color.length];
  }

  // Built-in defaults

  var defaults = {
    lines: 12,            // The number of lines to draw
    length: 7,            // The length of each line
    width: 5,             // The line thickness
    radius: 10,           // The radius of the inner circle
    scale: 1.0,           // Scales overall size of the spinner
    corners: 1,           // Roundness (0..1)
    color: '#000',        // #rgb or #rrggbb
    opacity: 1/4,         // Opacity of the lines
    rotate: 0,            // Rotation offset
    direction: 1,         // 1: clockwise, -1: counterclockwise
    speed: 1,             // Rounds per second
    trail: 100,           // Afterglow percentage
    fps: 20,              // Frames per second when using setTimeout()
    zIndex: 2e9,          // Use a high z-index by default
    className: 'spinner', // CSS class to assign to the element
    top: '50%',           // center vertically
    left: '50%',          // center horizontally
    shadow: false,        // Whether to render a shadow
    hwaccel: false,       // Whether to use hardware acceleration
    position: 'absolute'  // Element positioning
  };

  /** The constructor */
  function Spinner(o) {
    this.opts = merge(o || {}, Spinner.defaults, defaults);
  }

  // Global defaults that override the built-ins:
  Spinner.defaults = {};

  merge(Spinner.prototype, {
    /**
     * Adds the spinner to the given target element. If this instance is already
     * spinning, it is automatically removed from its previous target b calling
     * stop() internally.
     */
    spin: function(target) {
      this.stop();

      var self = this;
      var o = self.opts;
      var el = self.el = createEl(null, {className: o.className});

      css(el, {
        position: o.position,
        width: 0,
        zIndex: o.zIndex,
        left: o.left,
        top: o.top
      });

      if (target) {
          target.insertBefore(el, target.firstChild || null);
          target.className = "fade";
      }

      el.setAttribute('role', 'progressbar');
      self.lines(el, self.opts);

      if (!useCssAnimations) {
        // No CSS animation support, use setTimeout() instead
        var i = 0;
        var start = (o.lines - 1) * (1 - o.direction) / 2;
        var alpha;
        var fps = o.fps;
        var f = fps / o.speed;
        var ostep = (1 - o.opacity) / (f * o.trail / 100);
        var astep = f / o.lines;

        (function anim() {
          i++;
          for (var j = 0; j < o.lines; j++) {
            alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity);

            self.opacity(el, j * o.direction + start, alpha, o);
          }
          self.timeout = self.el && setTimeout(anim, ~~(1000 / fps));
        })();
      }
      
      return self;
    },

    /**
     * Stops and removes the Spinner.
     */
    stop: function() {
      var el = this.el;
      if (el) {
        clearTimeout(this.timeout);
        if (el.parentNode) {
            var reg = new RegExp('(\\s|^)fade(\\s|$)');
            el.parentNode.className = el.parentNode.className.replace(reg, ' ');
            el.parentNode.removeChild(el);
        }
        this.el = undefined;
      }
      return this;
    },

    /**
     * Internal method that draws the individual lines. Will be overwritten
     * in VML fallback mode below.
     */
    lines: function(el, o) {
      var i = 0;
      var start = (o.lines - 1) * (1 - o.direction) / 2;
      var seg;

      function fill(color, shadow) {
        return css(createEl(), {
          position: 'absolute',
          width: o.scale * (o.length + o.width) + 'px',
          height: o.scale * o.width + 'px',
          background: color,
          boxShadow: shadow,
          transformOrigin: 'left',
          transform: 'rotate(' + ~~(360/o.lines*i + o.rotate) + 'deg) translate(' + o.scale*o.radius + 'px' + ',0)',
          borderRadius: (o.corners * o.scale * o.width >> 1) + 'px'
        });
      }

      for (; i < o.lines; i++) {
        seg = css(createEl(), {
          position: 'absolute',
          top: 1 + ~(o.scale * o.width / 2) + 'px',
          transform: o.hwaccel ? 'translate3d(0,0,0)' : '',
          opacity: o.opacity,
          animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite'
        });

        if (o.shadow) ins(seg, css(fill('#000', '0 0 4px #000'), {top: '2px'}));
        ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)')));
      }
      return el;
    },

    /**
     * Internal method that adjusts the opacity of a single line.
     * Will be overwritten in VML fallback mode below.
     */
    opacity: function(el, i, val) {
      if (i < el.childNodes.length) el.childNodes[i].style.opacity = val;
    }

  });


  function initVML() {

    /* Utility function to create a VML tag */
    function vml(tag, attr) {
      return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr);
    }

    // No CSS transforms but VML support, add a CSS rule for VML elements:
    sheet.addRule('.spin-vml', 'behavior:url(#default#VML)');

    Spinner.prototype.lines = function(el, o) {
      var r = o.scale * (o.length + o.width);
      var s = o.scale * 2 * r;

      function grp() {
        return css(
          vml('group', {
            coordsize: s + ' ' + s,
            coordorigin: -r + ' ' + -r
          }),
          { width: s, height: s }
        );
      }

      var margin = -(o.width + o.length) * o.scale * 2 + 'px';
      var g = css(grp(), {position: 'absolute', top: margin, left: margin});
      var i;

      function seg(i, dx, filter) {
        ins(
          g,
          ins(
            css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}),
            ins(
              css(
                vml('roundrect', {arcsize: o.corners}),
                {
                  width: r,
                  height: o.scale * o.width,
                  left: o.scale * o.radius,
                  top: -o.scale * o.width >> 1,
                  filter: filter
                }
              ),
              vml('fill', {color: getColor(o.color, i), opacity: o.opacity}),
              vml('stroke', {opacity: 0}) // transparent stroke to fix color bleeding upon opacity change
            )
          )
        );
      }

      if (o.shadow)
        for (i = 1; i <= o.lines; i++) {
          seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)');
        }

      for (i = 1; i <= o.lines; i++) seg(i);
      return ins(el, g);
    };

    Spinner.prototype.opacity = function(el, i, val, o) {
      var c = el.firstChild;
      o = o.shadow && o.lines || 0;
      if (c && i + o < c.childNodes.length) {
        c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild;
        if (c) c.opacity = val;
      }
    };
  }

  if (typeof document !== 'undefined') {
    sheet = (function() {
      var el = createEl('style', {type : 'text/css'});
      ins(document.getElementsByTagName('head')[0], el);
      return el.sheet || el.styleSheet;
    }());

    var probe = css(createEl('group'), {behavior: 'url(#default#VML)'});

    if (!vendor(probe, 'transform') && probe.adj) initVML();
    else useCssAnimations = vendor(probe, 'animation');
  }

  return Spinner;

}));

spin.js

改動的兩個地方:
(1)初始化的時候,如果是顯示,則給對應的標籤加上fade樣式

(2)每次都將fade樣式刪除掉。

改好之後,就是測試界面了。

    
    
    
    

    
    
    
    



    
查詢條件
test_spin.cshtml

使用說明:如果你的頁面不使用jQuery,引用spin.js這個文件,這個文件不需要jquery的支持;如果想要使用jQuery,則引用jquery.spin.js文件。上面的代碼是不使用jQuery的情況。組件需要定義一個空的div,然後在此div上面做初始化。得到的效果如下:

當然,如果你對此效果不滿意,你還可以設置遮罩層的透明度,以及整個遮罩的樣式。還有旋轉的各個參數,都可以通過初始化的時候自定義,上述代碼裏面有詳細註釋。

炫酷型

jquery.shCircleLoader.js組件
此組件效果不用說,使用也比較簡單,但是對IE10以下版本不支持。看看效果先:

至於具體的代碼使用,博主不打算深究,可以去百度或者github上面找找。

fakeLoader.js組件
更多的選擇,更好的扁平化效果,更好的手機、平板設備體驗。只需要看看圖片感受下就知道了。開源地址

流程圖小插件

前段時間做一個工作流的需求,需要顯示當前流程進行到哪一步,找到了一個流程小插件ystep。此組件優點在於使用簡單、夠輕量級。

效果展示

先來看看效果

藍色縮小版

源碼說明

開源地址

代碼示例

首先引用必須的文件





這個組件需要jQuery和bootstrap兩個組件的支持。

然後定義一個空的div

最後在點擊按鈕的時候初始化組件

    

如果是動態步驟,可能需要動態去構造steps屬性。然後通過setStep()設置當前到了哪一步。

常用方法:

//跳轉到下一個步驟
$(".ystep1").nextStep();
//跳轉到上一個步驟
$(".ystep1").prevStep();
//跳轉到指定步驟
$(".ystep1").setStep(2);
//獲取當前在第幾步
$(".ystep1").getStep();

按鈕提示組件bootstrap-confirmation

按鈕提示組件有點類似js裏面confirm的功能,不過這個confirm是以一種tooltip的方式彈出來的效果,給用戶一個確定、取消的判斷,界面更加友好。介紹這個組件之前,可以先來看看bootstrap裏面提示框的效果:

bootstrap-confirmation組件就是基於這個提示框的效果來實現的。github上面有好多個bootstrap-confirmation組件,但基本大同小異。

效果展示

最原始的效果

自定義title、按鈕文本

代碼示例

(1)引用文件:



  • 樣式需要bootstrap.css的支持
  • JavaScript需要jquery和bootstrap.js的支持。

(2)對應的點擊標籤(可以是任意標籤)


(3)js初始化


(4)更多屬性、事件、方法

除了上述初始化的屬性,還有一些常用的屬性。比如:

  • btnOkClass:確定按鈕的樣式;
  • btnCancelClass:取消按鈕的樣式;
  • singleton:是否只允許出現一個確定框;
  • popout:當用戶點擊其他地方的時候是否隱藏確定框;

比如你可以將btnOkClass設置成 btnOkClass : 'btn btn-sm btn-primary'

圖片分類、過濾組件MuxitUp

這是一個效果非常炫酷的分組、過濾組件,開源地址。博主在網上看到一個它的demo,覺得效果確實很好,廢話不多說,上圖。

原文地址:http://www.cnblogs.com/landeanfen/p/5461849.html#_label2_0

發佈了14 篇原創文章 · 獲贊 21 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章