常见样式设计及DOM操作整理

    xiaoxiao2021-03-25  107

    css部分

    为不同链接添加不同样式

    a[href^="http"]{ padding-right: 20px; background: url(external.gif) no-repeat center right; } /* email */ a[href^="mailto:"]{ padding-right: 20px; background: url(email.png) no-repeat center right; } /* pdf */ a[href$=".pdf"]{ padding-right: 20px; background: url(pdf.png) no-repeat center right; }

    跨浏览器灰度图

    <svg xmlns="http://www.w3.org/2000/svg"> <filter id="grayscale"> <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"></feColorMatrix> </filter> </svg> <style> img{ filter: url(filters.svg#grayscale); /* Firefox 3.5+ */ filter: gray; /* IE6-9 */ -webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */ } </style>

    动画背景

    button{ background-image: linear-gradient(#5187c4, #1c2f45); background-size: auto 200%; background-position: 0 100%; transition: background-position 0.5s; } button:hover { background-position: 0 0; }

    清除浮动

    /*方法1*/ .clear-fix{ clear: both; display: block; height: 0; overflow: hidden; } /*IE*/ .clear{ overflow: auto; zoom: 1; /*IE6*/ } /*方法2*/ &:after{ content: ""; display: block; height: 0; overflow: hidden; clear: both; } /*方法3*/ /*将浮动元素用一个不浮动的 div 包裹起来*/

    表格宽度自适应

    td { white-space: nowrap; }

    任意阴影

    .box-shadow { background-color: #FF8020; width: 160px; height: 90px; margin-top: -45px; margin-left: -80px; position: absolute; top: 50%; left: 50%; } .box-shadow:after { content: ""; width: 150px; height: 1px; margin-top: 88px; margin-left: -75px; display: block; position: absolute; left: 50%; z-index: -1; -webkit-box-shadow: 0px 0px 8px 2px #000000; -moz-box-shadow: 0px 0px 8px 2px #000000; box-shadow: 0px 0px 8px 2px #000000; }

    文本宽度自适应

    pre { white-space: pre-line; word-wrap: break-word; }

    模糊文本

    .blurry-text { color: transparent; text-shadow: 0 0 5px rgba(0,0,0,0.5); }

    网页加载动画

    loading:after { overflow: hidden; display: inline-block; vertical-align: bottom; animation: ellipsis 2s infinite; content: "\2026"; } @keyframes ellipsis { from { width: 2px; } to { width: 15px; } }

    窗口漂浮物

    <marquee direction="down" width="250" height="200" behavior="alternate" style="border:solid"> <marquee behavior="alternate"> This text will fly </marquee> </marquee>

    解决 input:text 自动填充变黄的问题

    input:-webkit-autofill{ -webkit-box-shadow: 0 0 0px 10000px white inset !important; box-shadow: 0 0 0px 10000px white inset !important; }

    jQuery部分

    返回头部

    $('a.top').click(function (e) { e.preventDefault(); $(body).animate({scrollTop: 0}, 800); });

    预加载图片

    $.preloadImages = function () { for (var i = 0; i < arguments.length; i++) { $('<img>').attr('src', arguments[i]); } }; $.preloadImages('img/hover-on.png', 'img/hover-off.png');

    自动替换加载失败的图片

    $('img').on('error', function () { $(this).prop('src', 'img/broken.png'); });

    切换元素的各种样式

    $('.btn').hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); });

    禁用/启用提交按钮

    $('input[type="submit"]').prop('disabled', true); $('input[type="submit"]').prop('disabled', false);

    组织默认事件

    $('a.no-link').click(function (e) { e.preventDefault(); });

    切换动画

    //淡入淡出 $('.btn').click(function () { $('.element').fadeToggle('slow'); }); //滑入滑出 $('.btn').click(function () { $('.element').slideToggle('slow'); });

    简单的手风琴样式

    $('#accordion').find('.content').hide(); //关闭全部标签 $('#accordion').find('.accordion-header').click(function () { var next = $(this).next(); next.slideToggle('fast'); $('.content').not(next).slideUp('fast'); return false; });

    调整多个 div 一样高

    var $columns = $('.column'); var height = 0; $columns.each(function () { if ($(this).height() > height) { height = $(this).height(); } }); $columns.height(height);

    同链接不同样式

    $('a[href^="http"]').attr('target', '_blank'); $('a[href^="//"]').attr('target', '_blank'); $('a[href^="' + window.location.origin + '"]').attr('target', '_self'); //cannot work in IE10 $("a[href$=pdf]").addClass('pdf'); $("a[href$=doc]").addClass('doc'); $("a[href$=xls]").addClass('xls');

    通过内容查找元素

    var search = $('#search').val(); $('div:not(:contains("' + search + '"))').hide();

    当其他元素获得焦点时触发

    $(document).on('visibilitychange', function (e) { if (e.target.visibilityState === "visible") { console.log('Tab is now in view!'); } else if (e.target.visibilityState === "hidden") { console.log('Tab is now hidden!'); } });

    显示 Ajax 错误信息

    $(document).ajaxError(function (e, xhr, settings, error) { console.log(error); });

    禁用右键菜单

    $(document).ready(function(){ $(document).bind("contextmenu", function(e){ e.preventDefault(); }) })

    模拟 placeholder 属性

    $(document).ready(function(){ var $input_text = $("input[type=text]"); $input_text.val("Enter your words here..."); var originalValue = input.val(); input.focus(function(){ if($.trim(input.val()) == originalValue){ input.val(""); } }).blur(funtion(){ if($.trim(input.val()) == ""){ input.val(originalValue); } }); });

    判断元素是否存在

    $(document).ready(function(){ if($('#id').length){ //do sth. } });

    放大 标签面积

    $("div").click(function(){ window.loaction = $(this).find("a").attr("href"); return false; });

    根据浏览器大小选择不同的类

    $(document).ready(function(){ $(window).resize(function(){ if($(window).width() > 1200){ $('body').addClass('large'); } else { $('body').removeClass('large') } }); });

    自定义伪类选择器

    $.extend($.expr[':'], { moreThan500px:function(a){ return $(a).width > 500; } }); //create a pseudo selector ':moreThan500px'

    禁用 jQuery 所以动画

    $.fx.off = true;

    判断鼠标左右键

    $("#id").mousedown(function(e){ switch(e.witch){ case 1: //left click break; case 2: //middle click break; case 3: //right click break; default: break; } });

    回车提交表单

    $("input").keyup(function(e){ if(e.witch == 13 || e.keyCode == 13){ $("#submit").trigger('click'); } });

    配置 Ajax 的全局参数

    $("#load").ajaxStart(function(){ showLoading(); disableButton(); }).ajaxComplete(function() { hideLoading(); enableButton(); });

    用 siblings() 选择兄弟元素

    $("#nav li").click(function(){ $(this).addClass("active").sibling().removeClass('active'); });

    用 Firebug 输出日志

    jQuery.log = jQuery.fn.log = function(msg){ if(console){ console.log("%s, %o", msg, this); } return $(this); //链式调用 }

    CSS 钩子

    $.cssHooks['borderRadius'] = { get: function(ele, computed, extra){ //Read the value of -moz-border-radius, -webkit-border-radius, -o-border-radius, -ms-border-radius or border-radius depanding on browser. } set: function(ele, value){ //Set all the property above. } };

    限制 textarea 的文字数量

    jQuery.fn.maxLength = function(max){ this.each(function(){ var type = this.tagName.toLowerCase(); var inputType = this.type ? this.type.toLowerCase() : null; if(type == "input" && inputType == "text" || inputType == "password"){ this.maxLength = max; //use normal length } else if(type == "textarea"){ this.onkeypress = function(e){ var ob = e || window.event; var keyCode = ob.keyCode; var hasSelection - document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd; return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !ob.shiftKey && !hasSelection); }; this.onkeyup = function(){ if(this.value.length > max){ this.value = this.value.substring(0, max); } }; } }); };

    删除字符串中的 HTML 标签

    $.fn.stripHTML = function(){ var regexp = /<("[^"]*"|'[^']'|[^'">])*/gi; this.each(function(){ $(this).html($(this).html().replace(regexp, "")); }); return $(this); }

    使用 proxy() 函数代理

    $("panel").fadeIn(function(){ $("panel button").click(function(){ $(this).fadeOut(); //'this' is button, not panel }); $("panel button").click($.proxy(function(){ $(this).fadeOut(); //'this' is panel, not button }, this)); });

    禁用前进后退按钮

    $(document).ready(function(){ window.history.forward(1); window.history.forward(-1); })

    javascript 部分

    类数组对象转化为数组

    function trans(obj){ return [].slice.call(obj); } //以下是 ES6 方法 function trans(obj){ return Array.from(obj); }

    判断 浏览器 js 版本(鸭式辩型)

    //js版本检测 var JS_ver = []; (Number.prototype.toFixed)?JS_ver.push("1.5"):false; ([].indexOf && [].forEach)?JS_ver.push("1.6"):false; ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false; ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false; ("".trimLeft)?JS_ver.push("1.8.1"):false; JS_ver.supports = function() {   if (arguments[0])     return (!!~this.join().indexOf(arguments[0] +",") +",");   else     return (this[this.length-1]); } console.log("Javascript version supported in this browser: "+ JS_ver.supports());

    获取 url 中参数

    function getURIData(url){ var para = url.slice(url.indexOf('?') + 1); var reg = /&?(\w*)=([%\w]*)/g; var temp, data = {}; while(temp = reg.exec(para)){ data[temp[1]] = window.decodeURIComponent(temp[2]); } return data; }

    利用 documentFragment 避免多次刷新 DOM

    (function createList() {   var lis = ["first item", "second item", "third item",   "fourth item", "fith item"];   var Frag = document.createDocumentFragment();   while (lis.length) {     var li = document.createElement("li");     li.appendChild(document.createTextNode(lis.shift()));     Frag.appendChild(li);   }   document.getElementById('myUL').appendChild(Frag); })();
    转载请注明原文地址: https://ju.6miu.com/read-22644.html

    最新回复(0)