【整理】【精华】【实用】常用代码片段(二)https://developer.aliyun.com/article/1476776
/**将form表单各个参数组合为字符串形式*/ /**获取指定form中的所有的<input>对象*/ function getElements(formId) { var form = document.getElementById(formId); var elements = []; var tagElements = form.getElementsByTagName('input'); for (var j = 0; j < tagElements.length; j++) { elements.push(tagElements[j]); } var tagElements = form.getElementsByTagName('select'); for (var j = 0; j < tagElements.length; j++) { elements.push(tagElements[j]); } var tagElements = form.getElementsByTagName('textarea'); for (var j = 0; j < tagElements.length; j++) { elements.push(tagElements[j]); } return elements; }
/**组合URL*/function serializeElement(element) { var method = element.tagName.toLocaleLowerCase(); var parameter; if (method == 'select') { parameter = [element.name, element.value]; } switch (element.type.toLocaleLowerCase()) { case 'submit': case 'hidden': case 'password': case 'text': case 'date': case 'textarea': parameter = [element.name, element.value]; break; case 'checkbox': case 'radio': if (element.checked) { parameter = [element.name, element.value]; } break; } if (parameter) { var key = encodeURIComponent(parameter[0]); if (key.length == 0) return; if (parameter[1].constructor != Array) parameter[1] = [parameter[1]]; var values = parameter[1]; var results = []; for (var i = 0; i < values.length; i++) { results.push(key + '=' + encodeURIComponent(values[i])); } return results.join('&'); } }
/**调用方法*/ function formToConnectionParameters(formId) { var elements = getElements(formId); var queryComponents = []; for (var i = 0; i < elements.length; i++) { var queryComponent = serializeElement(elements[i]); if (queryComponent) { queryComponents.push(queryComponent); } } return queryComponents.join('&'); }
/**form表单是否有未填写内容*/ function formHasNull(formId) { var form = document.getElementById(formId); for (var i = 0; i < form.elements.length; i++) { var feled = form.elements[i]; switch (feled.type) { case undefined: case 'button': case 'file': case 'reset': case 'submit': break; case 'checkbox': case 'radio': if (!feled.checked) { return true; break; } default: if (feled.value.replace(/\ |\ /g, "") == "") { return true; break; } } } return false; }
<!--路由--> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> <script src="http://cdn.staticfile.org/angular-ui-router/0.2.11/angular-ui-router.min.js"></script> <script> var myApp = angular.module("myApp", ["ui.router"]); myApp.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.when("", "/home").otherwise("/404"); $stateProvider .state("home", {url: "/home", template: "<h1>首页</h1>"})//可以直接写html .state("about", {url: "/about", templateUrl: "about.html"})//也可以传递外部html,该html里面无需写html、body、head标签 .state("contacts", { url: "/contacts", template: "<h1>联系我们</h1>"//可以通过resolve预加载依赖的外部js /**, resolve: { deps: ['uiLoad', function (uiLoad) { return uiLoad.load(['js/name1.js', 'js/name2.js']); //需要依赖ui-load.js }] }*/ }); }); </script> <div ng-app="myApp"> <a ui-sref="home">home</a> <a ui-sref="about">about</a> <a ui-sref="contacts">contacts</a> <div ui-view></div> </div>
/**递归循环方法(可设置delay延时递归)*/ function dg(arr, i, delay) { i || (i = 0), delay || (delay = 0); var a = arr[i]; //这里写代码 i++, setTimeout(function () { i < arr.length && dg(arr, i, delay); }, delay) } var arr = dg(arr);
//点击全局页面其他部分→隐藏指定DOM document.onmousedown = function(e) { e.path.indexOf(指定DOM) == -1 && 隐藏方法(); };
//顶部导航条(菜单)随着滚动条隐藏:1、滚动条往下隐藏导航条;2、滚动条往上显示导航条 var initScroll = function () { var nav = document.querySelector("导航条"), nh = nav.offsetHeight, beforeScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0, html = document.querySelector("html"); onscroll = function () { var afterScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0, hy = html.getBoundingClientRect().y; if (afterScrollTop > beforeScrollTop && hy < -nh) { nav.style.marginTop = -1 * nh + "px"; hy < -window.innerHeight && 显示返回顶部按钮(); } else { nav.style.marginTop = 0; 隐藏返回顶部按钮(); } beforeScrollTop = afterScrollTop; } }; initScroll();
/*获取子DOM元素在父元素里面的索引位置(是第几个元素)*/ function getNodeListIndex(childNode) { return childNode && childNode.parentNode ? Array.prototype.indexOf.call(childNode.parentNode.children, childNode) : null; }
<!-- 自定义虚线/实线样式 --> <hr class="sg-hr" /> <style> .sg-hr,hr { border: none; height: 0; width: 100%; border-top: 2px solid #f3f3f3; margin: 20px 0 10px 0; } </style>
<!--原生表格纵向滚动条--> <style> thead, tbody { display: block; } tbody { overflow-y: auto; max-height: 100px; /*正文表格最大高度*/ } </style> <table> <thead> <tr> <td>表头1</td> <td>表头2</td> </tr> </thead> <tbody> <tr> <td>内容1</td> <td>内容2</td> </tr> <tr> <td>内容1</td> <td>内容2</td> </tr> <tr> <td>内容1</td> <td>内容2</td> </tr> <tr> <td>内容1</td> <td>内容2</td> </tr> <tr> <td>内容1</td> <td>内容2</td> </tr> </tbody> </table>
/*任意字符串转为像素单位*/ var getPx = function (num) { num || (num = 0), num = num.toString().toLowerCase(); return num + ((num.indexOf('px') > -1 || num.indexOf('%') > -1) ? '' : 'px'); }
/*获取鼠标移动方向*/ function getMouseDirection(sel) { var wrap = document.querySelector(sel); var hoverDir = function (e) { var w = wrap.offsetWidth, h = wrap.offsetHeight, x = (e.clientX - wrap.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1), y = (e.clientY - wrap.offsetTop - (h / 2)) * (h > w ? (w / h) : 1), direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; /* 上(0) 右(1) 下(2) 左(3)*/ console.log(direction); } if (window.addEventListener) { wrap.addEventListener('mousemove', hoverDir, false); } else if (window.attachEvent) { wrap.attachEvent('mousemove', hoverDir); } } getMouseDirection('body');
/*DOM类型判断*/ var isDOM = (typeof HTMLElement === 'object') ? function (obj) { return obj instanceof HTMLElement; } : function (obj) { return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string'; } /*获取DOM*/ var __getDOM = function (dom) { return (typeof dom == 'string' ? document.querySelector(dom) : dom) || null; }
//自由化传参【可以传入数组、离散的独立参数】 var __getFreeParams = function (args) { var ra = [], arr = Array.isArray(args) ? args : arguments; for (var i = 0, len = arr.length; i < len; i++) { var a = arr[i]; a != undefined && ra.push(a); } return ra; } console.log(__getFreeParams(1, 2, 3, 4));
/*监听DIV内容发生变化*/ function addChangeListener(sel, changeEvent) { document.querySelector(sel).addEventListener('DOMNodeInserted', function () { changeEvent(this.innerHTML); }); };
//在DOM开头加渲染 function insertBefore(sel, html) { document.querySelector(sel).insertAdjacentHTML("afterbegin", html); } /*js实现jquery的append方法*/ //在DOM结尾追加渲染 function append(sel, html) { document.querySelector(sel).insertAdjacentHTML("beforeend", html); }
dom.scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"});//缓慢滚动 /** 【behavior 可选】 定义动画过渡效果, "auto", "instant", 或 "smooth" 之一。默认为 "auto"。 【block 可选】 定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"。 【inline 可选】 定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"。 */ $('html').stop().animate({scrollTop: 滚动顶部位置}, 'fast', function () {console.log('滚动结束');});
//获取伪元素的样式 var getPseudoElementStyle = function (sel, pseudo, propertyName) { return window.getComputedStyle(document.querySelector(sel), ':' + (pseudo || 'before')).getPropertyValue(propertyName || 'display'); }; console.log(getPseudoElementStyle('h1', 'after', 'content'));//测试
/*全站变成灰色(去色)*/ * { filter: grayscale(100%); -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grayscale(100%); -o-filter: grayscale(100%); filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1); -webkit-filter: grayscale(1); }
&::after { /* 向下的直角三角形箭头 */ content: ""; position: absolute; top: 0px; right: 0px; width: 0; height: 0; border: 5px solid transparent; border-top-color: red; } &::after { /* 向右的直角三角形箭头 */ content: ""; position: absolute; top: 0px; right: 0px; width: 0; height: 0; border: 5px solid transparent; border-left-color: red; }
//Vue在新窗口弹出单页面 const { href } = this.$router.resolve({ path: "/singleNewsDetail", query: { item: this.item, id: this.id } }); window.open(href, "_blank");
//Vue节点绑定事件获取当前元素,并修改其样式 @click="$event.srcElement.style.display='none'" // 当前点击的元素 $event.target;//等同于$event.srcElement // 绑定事件的元素 $event.currentTarget; // (target与currentTarget的区别主要体现在使用事件委托时,发生事件委托时,点击的元素与绑定事件的元素非同一元素,反之不发生事件委托时,两者相同,是同一元素) // 获得绑定事件元素的前一个节点信息(包含元素节点、属性节点、文本节点、注释节点) $event.currentTarget.previousSibling; // 获得绑定事件元素的前一个元素节点(只包含元素节点,只有html内容) $event.currentTarget.previousElementSibling; // 下一个元素信息获取使用 nextSibling、nextElementSibling // 获得绑定事件元素的父节点信息 $event.currentTarget.parentNode; // 获得绑定事件元素的父级元素 $event.currentTarget.parentElement; // 获得绑定事件元素的第一个子节点信息 $event.currentTarget.firstChild; // 获得绑定事件元素的第一个子元素 $event.currentTarget.firstElementChild; // 获得绑定事件元素中id为ceshi的元素集合 $event.currentTarget.getElementById("ceshi"); // 获得绑定事件元素中class为ceshi的元素集合 $event.currentTarget.getElementsByClassName("ceshi"); // 获得绑定事件元素的的内容(类似jquery的text()) $event.currentTarget.textContent; // 获得绑定事件元素的的内容(类似jquery的html()) $event.currentTarget.innerHTML; // 获得绑定事件元素的ceshi属性(类似jquery的attr('ceshi')) $event.currentTarget.getAttributeNode("ceshi"); // 点击删除当前元素 $event.currentTarget.parentElement.removeChild(event.currentTarget); // 点击删除当前元素的父级元素 $event.currentTarget.parentElement.parentElement.removeChild(event.currentTarget.parentElement);
/* 用白色渐变遮罩隐藏未显示完的文章部分 */ &::after { content: ""; position: absolute; left: 0; bottom: 0; width: 100%; height: 100px; /*从上往下渐变背景*/ background: -webkit-linear-gradient( transparent, white ); /* Safari 5.1 - 6.0 */ background: -o-linear-gradient( transparent, white ); /* Opera 11.1 - 12.0 */ background: -moz-linear-gradient( transparent, white ); /* Firefox 3.6 - 15 */ background: linear-gradient( transparent, white ); /* 标准的语法(必须放在最后) */ }
<!--Vue绑定html标签背景、样式--> :style="{backgroundImage:'url('+item.bgUrl+')'}" <!--根据索引值左右滑动--> :style="{marginLeft:-100*currentIndex+'px'}"
单行省略号 { /*单行省略号*/ overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } 多行省略号 { /*多行省略号*/ overflow: hidden; word-break: break-all;/*单词分割换行*/ display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 行数(默认3); height: 高度px; }
/*js代码添加省略号*/ function addEllipsis(text, maxLength=10, suffix="…") { text=text.toString(); return text.length > maxLength ? text.substr(0, maxLength - 1) + suffix : text; }
//递归把不同层级深度的数组元素转换为扁平化同一个层级的数组 function p(a, b = []) {Array.isArray(a) ? a.forEach(function (c) {p(c, b);}) : b.push(a);return b;} console.log(p([1, [2, [3, 4], 5], 6]));
<body alt = "屏蔽右键" oncontextmenu = "return false" ondragstart = "return false" onselectstart = "return false" ></body>
<!--循环自动播放背景音乐、隐藏播放器--> <audio controls="controls" autoplay loop hidden> <source src="sound/bg.mp3" type="audio/mpeg"/> </audio> <!--视频播放器--> <video id="video" src="video/1.mp4" poster="img/video-default-cover.jpg" controls controlsList="nodownload" autoplay loop width="100%" height="100%" >您的浏览器版本太陈旧了,赶紧去官网升级吧!</video>
//获取本地国家语言、语种类别 var lang = navigator.userLanguage||navigator.language;//常规浏览器或者IE本地化语言 lang = lang.toLowerCase().substr(0,2);//截取前两位支付 console.log(lang);
/*获取当前页面的最高层级*/ var getMaxZIndex = () => { var arr = [...document.all].map(e => +window.getComputedStyle(e).zIndex || 0); return arr.length ? Math.max(...arr) : 0; };
/*模糊*/filter: blur(5px);
<!--富文本编辑器【舒工强烈推荐的编辑器】(帮助文档请登录www.wangeditor.com)--> <!--SGeditor--> <div class="SGeditor"><p>请在此处输入描述内容…</p></div> <!--END SGeditor--> <!--SGeditor--> <script src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js"></script> <!--END SGeditor--> <script type="text/javascript">var E = window.wangEditor; var SGeditor = new E(".SGeditor"); SGeditor.customConfig.uploadImgServer = "/SGeditor-upload-img"; SGeditor.customConfig.uploadImgHooks = { customInsert: function (insertImg, result, editor) { console.log(JSON.stringify(result)); insertImg(result.data[0]); } }; /*SGeditor.customConfig.uploadImgParams = { a: 123, b: 'vvv' }, SGeditor.customConfig.uploadImgParamsWithUrl = true;*/ SGeditor.create(); </script>
/*自定义原生添加ClassName,模仿JQuery addClass() 方法*/ var Class = { __convertDOM: function (sel) { typeof sel == "string" && (sel = document.querySelector(sel)); return sel; }, has: function (sel, cls) { sel = this.__convertDOM(sel); return sel.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)")); }, add: function (sel, cls) { sel = this.__convertDOM(sel); if (!Class.has(sel, cls)) sel.className += " " + cls; }, remove: function (sel, cls) { sel = this.__convertDOM(sel); if (Class.has(sel, cls)) { var reg = new RegExp(cls, "g"); sel.className = sel.className.replace(reg, ""); } }, /*切换className*/ toggle: function (sel, cls) { sel = this.__convertDOM(sel); if (Class.has(sel, cls)) { Class.remove(sel, cls); } else { Class.add(sel, cls); } } }; /*测试用例*/ Class.toggle("body", "testClass");
/*scss循环*/ @for $i from 1 through length($数组) { $color: nth($数组, $i); &:nth-of-type(#{$i}) { color: $color; &:hover { color: white; } } }
/*图片填充文字背景*/ height: auto; width: auto; background: url(bg.png) no-repeat left center; background-origin: border-box; -webkit-background-clip: text; -webkit-text-fill-color: transparent; /*fillcolor是Webkit内核私有属性哦 */ /*渐变文字(仅谷歌内核浏览器支持)*/ background: -webkit-linear-gradient(white, black); -webkit-background-clip: text; -webkit-text-fill-color: transparent;
<!- vue for循环 -> v-for="(item,$index) in items" :key="$index" :hover="hoverIndex==$index" :current="currentIndex==$index" @mouseover="hoverIndex=$index,autoPlay=false" @mouseout="hoverIndex=null,autoPlay=localAutoPlay" @click="currentIndex=$index" v-html="item.label" <!- angular for循环 -> <li ng-repeat="item in items track by $index" ng-click=" ng-bind-html="item" > {{item}} </li>
// angularJS 用$loaction获取window.location信息 // open http://host.com/base/index.html#!/a $location.absUrl() == 'http://host.com/base/index.html#!/a'; $location.path() == '/a'; $location.path('/foo'); $location.absUrl() == 'http://host.com/base/index.html#!/foo'; $location.search() == {};//search没东东的时候,返回空对象 $location.search({a: 'b', c: true}); $location.absUrl() == 'http://host.com/base/index.html#!/foo?a=b&c'; $location.path('/new').search('x=y');//可以用字符串的方式更改search,每次设置search,都会覆盖之前的search $location.absUrl() == 'http://host.com/base/index.html#!/new?x=y';
/*强制关闭不提示*/ function CloseWebPage() { window.location.replace("about:blank"); window.opener = null; window.open('', '_self'); window.close(); }
var space = { /*去掉字符串前后空格*/trimSpace: function (str) { str || (str = ""); return str.replace(/(^\s*)|(\s*$)/g, ""); }, /*去掉字符串中所有空格(包括中间空格)*/trimAllSpace: function (str) { str || (str = ""); return str.replace(/\s+/g, ""); }, /*去掉所有全角半角空格*/ trimAllWholeCornerSpace: function (str) { str || (str = ""); return str.replace(/\ |\ /g, ""); }, /*去掉所有全角半角 空格*/ trimAllWholeCornerCodeSpace: function (str) { str || (str = ""); return this.trimAllWholeCornerSpace(str).replace(/ /g, ""); } };
/*转换为废代码文本(转换文本中的?<、>符号)*/ var replaceLTandGT = function (s) { if (s == null || s == undefined) return ""; return s.toString().replace(/</g, "<").replace(/>/g, ">"); };
/*边框渐变*/ border: 1px solid; border-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Safari 5.1 - 6.0 */ border-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Opera 11.1 - 12.0 */ border-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Firefox 3.6 - 15 */ border-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* 标准的语法(必须放在最后) */