Jquery常用插件及功能片段

巧了我就是萌 提交于 2020-03-25 06:17:41

3 月,跳不动了?>>>

返回顶部

输入图片说明

<style type="text/css">
.to-top {width:37px;height:36px;position:fixed;bottom:150px;right:40px;display:none;background-position-x:-37px;background-image:url(totop.png);	}
.to-top:hover {background-position-x:0px;}
</style>

<div class="to-top"></div>
<script type="text/javascript">
$(function(){
	$win   = $(window);
	$totop = $('.to-top');

	$win.scroll(function(){
	    if( $win.scrollTop()>100 ){
	        $totop.fadeIn('slow');
	    }else{
	        $totop.fadeOut('slow');
	    }
	});

	$totop.click(function(){
		$('body, html').animate({scrollTop:0}, 800);
	});
});
</script>

解决手机浏览器bfcache导致的后腿页面js不执行

window.addEventListener('pageshow', function(e){
    if (e.persisted) {
        window.location.reload();
    }
})

60S倒计时

function countdown($dom, seconds) {
    if (typeof(countdownTimer) == 'undefined') {
        var countdownTimer = function($dom) {
            if (countdownSeconds == 0) {
                $dom.prop('disabled', false).removeAttr('disabled').text(originText);
                return;
            } else {
                $dom.prop('disabled', true).attr('disabled', 'disabled').text('重新发送(' + countdownSeconds + ')');
                countdownSeconds--;
            }
            setTimeout(function(){countdownTimer($dom);}, 1000);
        }
    }

    var countdownSeconds = parseInt(seconds);
    var originText = $dom.text();
    countdownTimer($dom);
}

禁止浏览器后退

history.pushState(null, null, document.URL);

window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

飘入动画

<img id="actor" style="display:none;position:fixed">
var startOffset = $('.start').offset();
var endOffset = $('.end').offset();
$('#actor').attr('src', $(.start img).attr('src'))
			.css({
				top: startOffset.top + 'px',
				left: startOffset.left + 'px'
			})
			.show()
$('#actor').animate({
	top: endOffset.top + 'px',
	left: endOffset.left + 'px',
	width: '0px',
	height: '0px'
}, 500);

滚动底部加载更多评价

#jquery
$container.scroll(function(){
    if ($(this).scrollTop() >= this.scrollHeight - $(this).innerHeight()) {
        action();
    }
});

#zepto
$container.scroll(function(){
    if ($(this).scrollTop() >= $(this).get(0).clientHeight - $(this).height()) {
        action();
    }
});

Jquery.clone修复

修复部分浏览器在jquery.clone时 textarea 和 select 标签的值没有clone成功的bug

(function (original) {
    jQuery.fn.clone = function () {
        var result = original.apply(this, arguments),
            my_textareas = this.find('textarea').add(this.filter('textarea')),
            result_textareas = result.find('textarea').add(result.filter('textarea')),
            my_selects = this.find('select').add(this.filter('select')),
            result_selects = result.find('select').add(result.filter('select'));

        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
        for (var i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;

        return result;
    };
}) (jQuery.fn.clone);

复制到剪贴板(兼容IE8处理)

html

<a class="copy_link" href="javascript:void(0);" data-clipboard-text="hello world" aria-label="复制成功">复制地址</a>
<!--[if !IE]><!--><script type="text/javascript" src="clipboard.min.js?v=2"></script><!--><![endif]-->
<!--[if gte IE 9]><script type="text/javascript" src="clipboard.min.js?v=2"></script><![endif]-->

JS

        if ($.browser.msie && $.browser.version < '9.0') {
            $(document).delegate('.copy_link', 'click', function(){
                window.clipboardData.setData('hello world');
                alert('复制成功');
            });
        } else {
            var clipboard = new Clipboard('.copy_link');
            clipboard.on('success', function(e) {
                alert('复制成功');
                e.clearSelection();
            }).on('error', function(e) {
                alert('复制失败');
            });
        }


DataTable

<table id="link-table" class="table table-striped table-hover" width="100%"></table>
<script type="text/javascript">
var link_table = $("#link-table").dataTable({
    "bProcessing" : true, //加载时显示进度提示
    "bAutoWidth": false,
    "bStateSave" : true, //保存筛选状态
    "iDisplayLength": 10,
    "bLengthChange": false,
    "bFilter": false,
    "bServerSide": true,
    "sAjaxSource" : build_api(),
    "aoColumns": [
        {"sTitle": "id", "mData": "id", "bSortable": false},
        {"sTitle": "渠道", "mData": "channel", "bSortable": false},
        {"sTitle": "推广计划", "mData": "plan", "bSortable": false},
        {"sTitle": "推广组", "mData": "group", "bSortable": false},
        {"sTitle": "关键词", "mData": "keyword", "bSortable": false},
        {"sTitle": "投放路径", "mData": "uri", "bSortable": false},
        {"sTitle": "操作", "bSortable": false, "sDefaultContent": ''}
    ],
    "aoColumnDefs": [
        {
            "aTargets": [6],
            "mData": "id"
            "sWidth": "100px",
            "sClass": 'uri_td',
            "mRender": function(data, type, full) {
                var tpl = '<a class="edit-link" href="javascript:;" data-id={id}>修改</a> \
                            <a class="del-link" href="javascript:;" data-id={id}>删除</a> \
                            <a class="test-link" href="{link}" target="_blank">测试</a> \
                            <span class="dn" id={id}></span>';
                return tpl;
            }
        },
    ],
    "oLanguage":{
        "oPaginate": {
            "sFirst": "首页",
            "sLast": "末页",
            "sNext": "",
            "sPrevious": ""
        },
        "sProcessing": '<img src="/images/input-spinner.gif"/>',
        "sInfo": "",
        "sEmptyTable": "抱歉, 没有检索到数据",
        "sInfoEmpty": "没有数据",
        "sLengthMenu": "_MENU_ 条/页",
        "sInfoFiltered": ''
    },
    "fnDrawCallback": function( oSettings ) {
        //
    }
});
//检索后刷新datatable
$('#link-table-wrap').delegate('#search', 'click', function(){
    var oSettings = link_table.fnSettings();
    oSettings.sAjaxSource = build_api();
    link_table.fnDraw();
});
$('#link-table-wrap').delegate('.del-link', 'click', function(){
    if (!confirm("你确认要删除该行么?")) return false;

    var link_row = $(this).parents('tr')[0];
    var id = $(this).data('id');
    $.ajax({
        type: 'POST',
        url: '/delete',
        data: {id: id},
        dataType: 'json'
    }).then(function(resp){
        if (resp.ret != 1)
            return alert('删除失败');

        link_table.fnDeleteRow(link_row);
    });

    return false;
});
$('#link-table-wrap').delegate('.edit-link', 'click', function(){
    var link_row = $(this).parents('tr')[0];

    if (nEditing !== null) {
        if (nEditing != link_row) {
            /* Currently editing - but not this row - restore the old before continuing to edit mode */
            dataTable.restoreRow(link_table, nEditing);
            dataTable.editRow(link_table, link_row);
            nEditing = link_row;

        } else if (nEditing == link_row && $(this).text() == "保存") {
            /* Editing this row and want to save it */
            dataTable.saveRow(link_table, nEditing);
            nEditing = null;
        }
    }  else {
        /* No edit in progress - let's start one */
        dataTable.editRow(link_table, link_row);
        nEditing = link_row;
    }

    return false;
});
$('#link-table-wrap').delegate('#new-link', 'click', function(){
    $.ajax({
        type: 'POST',
        url: '/new',
        dataType: 'json'
    }).then(function(resp){
        if (resp.ret != 1)
            return alert('新增失败');

        link_table.fnDraw();
        setTimeout(function(){
            var nRow = $('span#'+resp.data.id).closest('tr')[0];
            dataTable.editRow(link_table, nRow);
            nEditing = nRow;
        }, 1000);
    });
});
var nEditing = null;
var dataTable = {
    restoreRow: function(oTable, nRow) {
                    var aData = oTable.fnGetData(nRow);
                    var jqTds = $('>td', nRow);

                    for (var key in aData) {
                        oTable.fnUpdate(aData[key], nRow, key, false);
                    }

                    oTable.fnDraw();
                },
    editRow: function(oTable, nRow) {
                    var aData = oTable.fnGetData(nRow);
                    var jqTds = $('>td', nRow);
                    //jqTds[0].innerHTML = '<input type="text" class="form-control small" value="' + aData[0] + '">';
                    jqTds[1].innerHTML = '<select class="form-control small field" value="'+aData['channel']+'"></select>';
                    jqTds[2].innerHTML = '<input type="text" class="form-control small field" value="' + aData['plan'] + '">';
                    jqTds[3].innerHTML = '<input type="text" class="form-control small field" value="' + aData['group'] + '">';
                    jqTds[4].innerHTML = '<input type="text" class="form-control small field" value="' + aData['keyword'] + '">';
                    jqTds[5].innerHTML = '<input type="text" class="form-control small field" value="' + aData['uri'] + '">';

                    $('select', nRow).html($('.channel option[value]').clone());

                    $('.edit-link', nRow).text('保存');
                },
    saveRow: function(oTable, nRow) {
                    var id = $('.edit-link', nRow).data('id');
                    var jqInputs = $('.field', nRow);

                    $.ajax({
                        type: 'POST',
                        url: 'update',
                        data: {
                            id: id,
                            'channel': jqInputs[0].value,
                            'plan': jqInputs[1].value,
                            'group': jqInputs[2].value,
                            'keyword': jqInputs[3].value,
                            'uri': jqInputs[4].value
                        },
                        dataType: 'json'
                    }).then(function(resp){
                        if (resp.ret != 1)
                            return alert('保存失败');

                        oTable.fnUpdate(jqInputs[0].value.trim(), nRow, 0, false);
                        oTable.fnUpdate(jqInputs[1].value.trim(), nRow, 1, false);
                        oTable.fnUpdate(jqInputs[2].value.trim(), nRow, 2, false);
                        oTable.fnUpdate(jqInputs[3].value.trim(), nRow, 3, false);
                        oTable.fnUpdate(jqInputs[4].value.trim(), nRow, 4, false);
                        oTable.fnDraw();
                    });

                }
};

//根据过滤项动态计算接口地址
function build_api(){
    var api = '/api';
    return api
}
</script>

DropZone

默认效果:
输入图片说明
选中文件:
输入图片说明
上传过程:
输入图片说明

插件请下载最新版,旧版有非常多的bug

<link rel="stylesheet" type="text/css" href="dropzone/dropzone.css">
<script type="text/javascript" src="dropzone/dropzone.js"></script>
<style type="text/css">
#upload-form {min-height: 200px;width: 800px;margin-right: -810px;margin-bottom: 30px;display: inline-block;}
#upload-form #uploadBtn {position: absolute;top: 2px;right: -294px;font-family: "方正舒体";font-size: 40px;width: 276px;height: 80px;cursor: pointer;}	
</style>

<form id="target" class="dropzone">
    <button id="uploadBtn" class="btn btn-success"> 确 认 上 传 </button>
</form>
<script type="text/javascript">
Dropzone.autoDiscover = false; //关闭自动初始化
/* Dropzone上传插件配置 */
$('#target').dropzone({
    url: '/upload',
    paramName: "signimage", //上传字段名
    maxFilesize: 2, // MB
    acceptedFiles: ".jpg,.jpeg,.png,.gif,.bmp",
    addRemoveLinks: true,
    clickable: true,
    autoProcessQueue: false, //关闭自动上传, 手动调度
    uploadMultiple: true,
    parallelUploads: 10, //最大并行处理量
    maxFiles: 100, //最大上传数量
    
    /* 插件消息翻译 */
    dictDefaultMessage: '<i class="fa fa-cloud-upload"></i>拖拉文件上传<br />或 <i class="fa fa-thumbs-down"></i>点此上传',
    dictInvalidFileType: '只支持图片文件上传',
    dictFileTooBig: '图片超出最大2M约束',
    dictMaxFilesExceeded: '超出最大上传数量',
    dictCancelUpload: '取消上传',
    dictRemoveFile: '去除文件',
    dictCancelUploadConfirmation: '确认取消上传',

    /* 上传缩略图预览模板 */
    previewTemplate: '  \
                        <div class="dz-preview dz-file-preview">    \
                          <div class="dz-details">  \
                            <div class="dz-filename"><span data-dz-name></span></div>   \
                            <div class="dz-size" data-dz-size></div>    \
                            <img data-dz-thumbnail />   \
                          </div>    \
                          <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div> \
                          <div class="dz-success-mark"><span>✔</span></div> \
                          <div class="dz-error-mark"><span>✘</span></div>   \
                          <div class="dz-error-message"><span data-dz-errormessage>""</span></div>  \
                        </div>  \
                     ',

    /* 初始化期间注册一些事件处理句柄 */
    init: function(){
        var self = this;

        /* 点击上传按钮开始ajax上传 */
        this.element.querySelector("button#uploadBtn").addEventListener("click", function(e) {
          e.preventDefault();
          e.stopPropagation();
          self.processQueue();
        });

        /* 上传成功后 */
        this.on("successmultiple", function(files, response) {
            $('#upload-form #uploadBtn').tooltip({
                title: response.info,
                trigger: 'manual',
                container: '#uploadBtn', //该行解决了一个排版问题
            }).tooltip('show');

            /* 刷新页面 */
            setTimeout(function(){
                window.location = response.url || window.location;
            }, 1200);
        });

        this.on("error", function(file, errorMessage){
            $(file.previewElement).find('[data-dz-errormessage]').html(errorMessage);
        });
    },
};
</script>

知微地图

微博传播分析平台知微大数据里抠出来的一张地图插件, 源码略做了些改动以调整气泡提示内容

插件下载,网盘链接 插件效果:
输入图片说明

<script src="js/plugin/map/jquery.tooltip.js" type = "text/javascript" ></script>
<script src="js/plugin/map/raphael-min.js" type = "text/javascript" ></script>
<script src="js/plugin/map/provincenew.js" type = "text/javascript" ></script>

<div class="map-wrap" style="position:relative;margin:auto;">
	<div class="province"></div>
	<img src="images/mapleft.png" style="position: absolute;bottom:40px;left:20%;">
</div>
<script type="text/javascript">
$(".province").empty();
(new UI.ProvinceView(
	$('.province')[0],
	{width:1200,height:400},
	‘花冠’,  #排名上方标题
)).render([
	{docsCount: 2, name: "甘肃省", rank: 1, rate: 12, value: 12},
	...
]);
</script>

select2

插件效果:
输入图片说明
插件下载,网盘链接

<link rel="stylesheet" type="text/css" href="select2-3.4.8/select2.css" />
<link rel="stylesheet" type="text/css" href="select2-3.4.8/select2-bootstrap.css" />
<script type="text/javascript" src="select2-3.4.8/select2.min.js"></script>
<input type="hidden" class='drop' />
<script type="text/javascript">
// 硬编码数据初始化用法
$('.drop').select2({
			placeholder: '请选择品牌',
			allowClear: true,
			width: '150',
			data: [{id:0,text:'加载中',disabled:true}, {id:1,text:'第一条目'}],
			formatResult:    function(state){return '<img src="select2-3.4.8/select2-spinner.gif" style="vertical-align: middle;display:inline;" />' + state.text;},
			formatSelection: function(state){return '<img src="select2-3.4.8/select2-spinner.gif" style="vertical-align: middle;display:inline;" />' + state.text;},
		});	


// 关键字实时搜索用法
$('.drop').select2({
	placeholder: '请选择车型',
	allowClear: true,
	width: '150',
	minimumInputLength: 1,
	query: function(query){
		var keyword = query.term;

		$.ajax()
	         .then(function(results){
			query.callback({results:results});
		 });
},


// 设定下拉的选中项用法
$('.drop').select2('val', 数据项id);
</script>

Fuelux Tree

<div id="sem-tree" class="tree tree-plus-minus">
    <div class = "tree-folder" style="display:none;">
        <div class="tree-folder-header">
            <i class="fa fa-folder"></i>
            <div class="tree-folder-name"></div>
        </div>
        <div class="tree-folder-content"></div>
        <div class="tree-loader" style="display:none"></div>
    </div>
    <div class="tree-item" style="display:none;">
        <i class="tree-dot"></i>
        <div class="tree-item-name"></div>
    </div>
</div>
$('#sem-tree').tree({
    loadingHTML: '<img src="/images/input-spinner.gif"/>',
    dataSource: {
        data: function (options, callback) {
            $.ajax({
                type: 'GET',
                url: '/list',
                cache: false,
                dataType: 'json'
            }).then(function (resp) {
                    var list = resp.map(function (item) {
                    var nodetype = true;
                    return {
                        name: item.node,
                        type: nodetype ? 'item' : 'folder'
                    };
                });
                callback({data: list});
            });
        }
    }
});

冻结弹层下面的窗口滚动

.freeze-body {position:fixed;height:100%;overflow: hidden;}

移动端开发常用代码片段整理

JqueryMobile固定头部尾部

<header data-role="header" data-potision="fixed" data-tap-toggle="false">

<footer data-role="footer" data-position="fixed" data-tap-toggle="false">

H5页面html头部设定

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="pragma" content="no-cache" >
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!