1,getElementsByClassName
首先这是HTML5 DOM中新增的一个已久的方法,所有部分旧的浏览器有可能不支持
一般用法:var element = document.getElementsByClassName('元素');获得的是一个集合,需要循环遍历元素;
为了得到兼容,我们可以封装下这个方法来方便我们使用;
function getElementsByClassName(ele,calssname){
if(ele.getElementsByClassName){
return ele.getElementsByClassName(classname);
}else{
var _results = new Array(),
_elems = ele.getElementsByTagName('*');
for(var i=0,len=_elems.length;i<len;i++){
if(_elems[i].className.indexOf(classname) != -1){
_results[_results.length] = _elems[i];
}
}
return _results;
}
}
解释下:这个getElementsByClassName函数接受两个参数,第一个ele表示DOM树中的搜索起点,第二个calssname就是要搜索的类名了。(提示,这个例子不使用多个类名)
用法例子:
var myId = document.getElementById(id);
var myClass = getElementsByClassName(myId,'className');
2,onload
我们都知道onload事件只能执行一次,所以假设你要运行两个onload时候执行的函数,最后只能执行后一个onload事件的函数,那么我们如何执行多个onload事件的函数呢,
形式如下:
window.onload = function(){
num1();
num2();
}
所以,我们就顶一个函数addLoadEvent(func),它只接受参数,就是在页面加载完毕时执行的函数的名字
function addLoadEvent(func){
var oldonload = window.onload; //把现在有window.onload事件处理函数的值存入变量oldonload。
if(typeof window.onload != 'function'){ //如果这个处理函数还没有绑定任何函数,就像平时那样把新函数添加给它
window.onload = func;
}else{ //如果在这个处理函数上已经绑定了一些函数。就把新函数追加到现有指令的末尾
window.onload = function(){
oldonload();
func();
}
}
}
调用:
addLoadEvent(num1);
addLoadEvent(num2);
3,trigger
模拟jquery中的trigger()事件;
var trigger = function (ele, method) {
var func = ele[method];
return func();
};
调用方式:
trigger(document.getElementById('...'),'onclick');
4,trim去除前后空格
function trim(str){ //删除左右两端的空格
return str.replace(/(^\s*)|(\s*$)/g, '');
}
5,禁止鼠标滑轮滚动
//禁止鼠标滚轮滚动
function disabledMouseWheel() {
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
}//W3C
window.onmousewheel = document.onmousewheel = scrollFunc;//IE/Opera/Chrome
}
function scrollFunc(evt) {
evt = evt || window.event;
if (evt.preventDefault) {
// Firefox
evt.preventDefault();
evt.stopPropagation();
} else {
// IE
evt.cancelBubble = true;
evt.returnValue = false;
}
return false;
}
window.onload = disabledMouseWheel;
6,原生js实现在元素后面插入一个元素
function insertAfter(newElement, targetElement){
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement) {
// 如果最后的节点是目标元素,则直接添加。因为默认是最后
parent.appendChild(newElement);
}
else {
parent.insertBefore(newElement, targetElement.nextSibling);
//如果不是,则插入在目标元素的下一个兄弟节点 的前面。也就是目标元素的后面
}
}
7,getQueryString()获取url参数的值
function getQueryString(key,func){
if(!key || typeof key == 'undefined'){
key = '';
return null;
}else {
key = key.toLowerCase();
var _reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)'),
_search = window.location.search.toLowerCase().substr(1).match(_reg);
if(_reg !== null){
if(!func || func === '' || func ==='decodeURI' || typeof (func) === 'undefined'){
return decodeURI(_search[2]);
}else if(func === 'unescape'){
return unescape(_search[2]);
}else if(func === 'decodeURIComponent'){
return decodeURIComponent(_search[2]);
}
}else{
return null;
}
}
}
8,Cookie的设置,读取,删除
/*设置cookie*/
function setCookie(name, value, iDay)
{
var _oDate=new Date();
_oDate.setDate(_oDate.getDate()+iDay);
document.cookie=name+'='+value+';expires='+_oDate;
};
/*使用方法:setCookie('user', 'andy', 11);*/
/*获取cookie*/
function getCookie(key,func)
{
var _cookies = document.cookie;
key += '=';
var _i = 0;
while (_i < _cookies.length) {
var _offset = _i + key.length;
if (_cookies.substring(_i, _offset) == key) {
var _endstr = _cookies.indexOf(';', _offset);
if (_endstr == -1) {
_endstr = _cookies.length;
}
var r = _cookies.substring(_offset, _endstr);
if (r !== null) {
if (!func || func === '' || func == 'decodeURI' || typeof (func) == 'undefined') {
console.log(decodeURI(r));
return decodeURI(r);
} else if (func == 'unescape') {
console.log(unescape(r));
return unescape(r);
} else if (func == 'decodeURIComponent') {
return decodeURIComponent(r);
}
} else {
return null;
}
}
_i = _cookies.indexOf(' ', _i) + 1;
if (_i === 0) {
return;
}
}
return null;
};
/*使用方法:getCookie('user')*/
/*删除cookie*/
function removeCookie(name)
{
setCookie(name, 1, -1); //-1就是告诉系统已经过期,系统就会立刻去删除cookie
};
/*使用方法:removeCookie('user')*/
9,SessionStorage存储的设置,读取,删除;
function setSessionStorage(key,val){
try{
sessionStorage.removeItem(key);
sessionStorage.setItem(key,val);
return 1;
}catch(e){
return 0;
}
}
function getSessionStorage(key){
try{
return sessionStorage.getItem(key);
}catch(e){
console.log(e.message);
return 0;
}
}
function removeSessionStorage(key){
try{
sessionStorage.removeItem(key);
}catch(e){
console.log(e.message);
return 0;
}
}
10,LocalStorage存储的设置,读取以及删除
function setLocalStorage(key,val){
try{
localStorage.removeItem(key);
localStorage.setItem(key,val);
return 1;
}catch(e){
console.log(e.message);
return 0;
}
}
function getLocalStorage(key){
try{
return localStorage.getItem(key);
}catch(e){
console.log(e.message);
return 0;
}
}
function removeLocalStorage(key){
try{
localStorage.removeItem(key);
}catch(e){
console.log(e.message);
return 0;
}
}
11,页面加载loading以及loading结束
function loading(){
var _doc = document,
_backUrl = 'javascript:history.go(-1)';
var _oldLoading = document.getElementById('loading');
if(_oldLoading !==null && typeof (_oldLoading) !== 'undefined'){
return;
}else{
var _fragment = _doc.createDocumentFragment(),
_loading = _doc.createElement('div');
_loading.className = 'loading';
_loading.id = 'loading';
var _loader = _doc.createElement('div');
_loader.className = 'loader';
var _p = _doc.createElement('p');
_p.innerHTML = '正在加载中...';
var _backBtn = _doc.createElement('a');
_backBtn.setAttribute('href',_backUrl);
_loading.appendChild(_loader);
_loading.appendChild(_backBtn);
_loader.appendChild(_p);
_doc.body.appendChild(_loading);
}
}
function enloading(){
var _doc = document,
_loading = _doc.getElementById('loading');
if(_loading !==null && typeof (_loading) !=='undefined'){
_doc.body.removeChild(_loading);
}
}
12,获得元素的样式
function getStyle(obj, attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}
else{
return getComputedStyle(obj,false)[attr];
}
}
调用:getStyle(document.getElementById(' '),'width');
13,判断滚动条是否滚动
// 滚动条是否滚动
var $topVal = 0,
$timer = null;
function isOnScroll(){
if($timer === null){// 未发起时,启动定时器,30秒执行1次
$timer = setInterval(isStopOnscroll,30);
}
$topVal = document.body.scrollTop;
}
function isStopOnscroll(){
// 判断此刻到顶部的距离是否和1秒前的距离相等
if($doc.body.scrollTop === $topVal){
console.log("scroll bar is stopping!");
clearInterval($timer);
$timer = null;
}
}
14,移动端有弹窗的时候禁止底部页面滚动
css:
.uzai-frozen{
height: 100%;
overflow: hidden;
}
js:
// 禁止页面滚动
function frozenHtml(){
$doc.getElementsByTagName('html')[0].classList.add('uzai-frozen');
$doc.getElementsByTagName('body')[0].classList.add('uzai-frozen');
}
// 释放页面滚动
function thawHtml(){
$doc.getElementsByTagName('html')[0].classList.remove('uzai-frozen');
$doc.getElementsByTagName('body')[0].classList.remove('uzai-frozen');
}
15,获取移动端屏幕的高度
// 获得当前屏幕的高度
var $clientHeight = document.documentElement.clientHeight,
$filter = $doc.getElementsByClassName('filter-all')[0];
$filter.style.height = $clientHeight + 'px';
16,移动端返回顶部动画(先快后慢)
var _asider = $doc.getElementsByClassName('right-banner')[0],
_back = _asider.getElementsByClassName('back-top')[0],
_timer = null,
_isStop = true,// 向上滚动中,用户是否滚动了滚轮;
_clientHeight = $doc.documentElement.clientHeight;
var _bodyScroll = function(){
var _osTop = $doc.documentElement.scrollTop || $doc.body.scrollTop;
if(_osTop >= _clientHeight){
_asider.style.display = 'block';
}else{
_asider.style.display = 'none';
}
if(!_isStop){
clearInterval(_timer);
}
_isStop = false;
};
addEventOnScroll(_bodyScroll);
_back.onclick = function(){
_timer = setInterval(function(){
// 获得滚动条距离顶部的距离
var _osTop = $doc.documentElement.scrollTop || $doc.body.scrollTop,
_speed = Math.floor(-_osTop / 2);
_isStop = true;
$doc.documentElement.scrollTop = $doc.body.scrollTop = _osTop + _speed;
if(_osTop === 0){
clearInterval(_timer);
}
},20);
}
17,移动端图片懒加载
var _img = document.getElementsByClassName('lazys');
for (var i = 0; i < _img.length; i++) {
if (_img[i].offsetTop < window.innerHeight + document.body.scrollTop) {
var src_ = _img[i].getAttribute('data-original');
_img[i].setAttribute('src', src_);
}
}
18,appendHTML()---意在把html字符串转成html节点
HTMLElement.prototype.appendHTML = function(html) {
var _divTemp = document.createElement("div"), _nodes = null
// 文档片段,一次性append,提高性能
, _fragment = document.createDocumentFragment();
_divTemp.innerHTML = html;
_nodes = _divTemp.childNodes;
for (var i=0, length=_nodes.length; i<length; i+=1) {
_fragment.appendChild(_nodes[i].cloneNode(true));
}
this.appendChild(_fragment);
// 清空内存
_nodes = null;
_fragment = null;
};
19,prependHTML:
var prependHTML = function(el, html) { var divTemp = document.createElement("div"), nodes = null , fragment = document.createDocumentFragment(); divTemp.innerHTML = html; nodes = divTemp.childNodes; for (var i=0, length=nodes.length; i<length; i+=1) { fragment.appendChild(nodes[i].cloneNode(true)); } // 插入到容器的前面 - 差异所在 el.insertBefore(fragment, el.firstChild); // 内存回收? nodes = null; fragment = null;};20,removeElement(ele)删除当前元素
var _removeElement = function(_element){
var _parentElement = _element.parentNode;
if(_parentElement){
_parentElement.removeChild(_element);
}
};
21,移动端实时监控input的值,例如input框内只能输入数字:_lowPrice.addEventListener('focus',function(){ var _str = ''; var _now = ''; var filter_time = function(){ var _time = setInterval(filter_staff_from_exist, 100); _lowPrice.addEventListener('blur',function(){ clearInterval(_time); }); }; var filter_staff_from_exist = function(){ _now = _lowPrice.value.replace('/[^d]+/g',''); _now = parseInt(_now,10); if(isNaN(_now)){ _now = ''; } _lowPrice.value = _now; if (_now != '' && _now != _str) { console.log(_now); } _str = _now; }; filter_time();});22,移动端有input框的时候,当input框获得焦点的时候,若此时滑动屏幕,
想要input框失去焦点(一般真对ios机,
因为ios机当是弹层里的input框的时候,此时如果滑动屏幕,焦点会来会跑);if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { var windowTop = 0; //初始话可视区域距离页面顶端的距离 _routerPlay.addEventListener('touchmove',function(){ var _scrolls = _routerPlay.scrollTop; if(_scrolls >= windowTop){ windowTop = _scrolls; var el = document.activeElement; if (el.nodeName.toLowerCase() == 'input') { el.blur(); return; } }else{ windowTop = _scrolls; var el = document.activeElement; if (el.nodeName.toLowerCase() == 'input') { el.blur(); return; } } });} else if (/(Android)/i.test(navigator.userAgent)) { var winHeight = window.innerHeight, bShowRec = true; window.addEventListener('resize', function (e) { });}
23,移动端当弹层里有滚动条的时候,禁止body层滚动目前测试ios问题不大,不过andriod机上有点问题,先把代码贴出来,谁有好的方法欢迎指导var _filter = $doc.getElementById('uzai-choose'), _choose = _filter.getElementsByClassName('choose')[0], _goCity = _choose.getElementsByClassName('go-city')[0];var startx, starty;//获得角度var getAngle = function (angx, angy) { return Math.atan2(angy, angx) * 180 / Math.PI;};//根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动var getDirection = function (startx, starty, endx, endy) { var angx = endx - startx; var angy = endy - starty; var result = 0; //如果滑动距离太短 if (Math.abs(angx) < 2 && Math.abs(angy) < 2) { return result; } var angle = getAngle(angx, angy); if (angle >= -135 && angle <= -45) { result = 1; } else if (angle > 45 && angle < 135) { result = 2; } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) { result = 3; } else if (angle >= -45 && angle <= 45) { result = 4; } return result;};var _bodyTop;var _flag = true;ele.addEventListener('touchstart', function (e) { startx = e.touches[0].pageX; starty = e.touches[0].pageY; _bodyTop = $doc.body.scrollTop;}, false);//手指离开屏幕ele.addEventListener('touchmove', function (e) { $doc.body.scrollTop = _bodyTop; e.stopPropagation(); var endx, endy; endx = e.changedTouches[0].pageX; endy = e.changedTouches[0].pageY; var direction = getDirection(startx, starty, endx, endy); switch (direction) { case 0: //console.log("未滑动!"); break; case 1: //console.log("向上!"); // 判断是否达到底部 if (ele.scrollTop + ele.clientHeight + 5>= ele.scrollHeight) { //console.log('已经达到底部'); e.preventDefault(); return false; } e.stopPropagation(); //console.log(e.target.className); break; case 2: //console.log("向下!"); // 判断是否达到顶部 var _scroTop = ele.scrollTop; if (_scroTop <= 0) { //console.log('已经到达顶部!'); e.preventDefault(); return false; } break; default: }}, false);ele.addEventListener('touchend',function(e){ $doc.body.scrollTop = _bodyTop; //alert('ni')});
24,移动端滑动页面的时候,如果像获得当前页面是第几个页,例如京东的页码分页var _arr = [];for(var i = 0,len = $pLi.length;i<len;i++ ){ var _top = $pLi[i].getBoundingClientRect().top; //元素顶端到可见区域顶端的距离 var _bottom = $pLi[i].getBoundingClientRect().bottom; var _se = document.documentElement.clientHeight; //浏览器可见区域高度。 if((_top <= _se) && (_bottom > 0) ) { var _cur = Number($pLi[i].getAttribute('data-cur-page')); _arr.push(_cur); var _num = Math.max.apply(null, _arr); _pag.innerHTML = _num; }}25,ajax原生封装
/** * 执行基本ajax请求,返回XMLHttpRequest * Ajax.request({ * url * async 是否异步 true(默认) * method 请求方式 POST or GET(默认) * data 请求参数 (键值对字符串) * success 请求成功后响应函数,参数为xhr * error 请求失败后响应函数,参数为xhr 11 * }); */ var Ajax = function () { function request(opt) { function fn() { } var url = opt.url || ''; // 获得url var async = opt.async !== false, method = opt.method || 'GET', data = opt.data || null, success = opt.success || fn, error = opt.failure || fn; method = method.toUpperCase(); // 默认都转换大写 if (method == 'GET' && data) { var args = ''; if (typeof data == 'string') { args = data; } else if (typeof data == 'object') { var arr = new Array(); for (var k in data) { var v = data[k]; arr.push(k + '=' + v); } args = arr.join('&'); } url += (url.indexOf('?') == -1 ? '?' : '&') + args; data = null; } // var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveObject('Microsoft.XMLHTTP'); var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ''; xhr.onreadystatechange = function () {// 当请求被发送到服务器时,需要执行一些基于响应的任务 _onStateChange(xhr, success, error); }; xhr.open(method, url, async);// 创建一个请求,并准备向服务器发送 if (method == 'POST') {// 如果是POST请求的时候,需要添加个请求消息头 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;'); } xhr.send(data);// 向服务器发送请求 return xhr; } function _onStateChange(xhr, success, failure) { if (xhr.readyState == 4) {// 请求已完成,且响应已就绪 var s = xhr.status;// 状态码 if (s >= 200 && s < 300) { success(xhr);// } else { failure(xhr); } } else { } } return { request: request }; }();26,URL参数设定相关方法
///设置浏览器URL function setUrl(url) { var _stateObject = {}; var _title = ''; history.pushState(_stateObject, _title, url); } //替换指定传入参数的值,paramName为参数,replaceWith为新值 function replaceParamVal(Url, paramName, replaceWith) { var pattern = paramName + '=([^&]*)'; var replaceText = paramName + '=' + replaceWith; if (Url.match(pattern)) { var re = eval('/(' + paramName + '=)([^&]*)/gi'); var tmp = Url.replace(re, paramName + '=' + replaceWith); return (tmp); } else { if (Url.match('[\?]')) { return Url + '&' + replaceText; } else { return Url + '?' + replaceText; } } return Url + '\n' + paramName + '\n' + replaceWith; } ///删除URL指定参数 function delQueStr(url, ref) //删除参数值 { var str = ''; if (url.indexOf('?') != -1){ str = url.substr(url.indexOf('?') + 1); } else{ return url; } var arr = ''; var returnurl = ''; var setparam = ''; if (str.indexOf('&') != -1) { arr = str.split('&'); for (var i in arr) { if (arr[i].split('=')[0] != ref) { returnurl = returnurl + arr[i].split('=')[0] + '=' + arr[i].split('=')[1] + '&'; } } return url.substr(0, url.indexOf('?')) + '?' + returnurl.substr(0, returnurl.length - 1); } else { arr = str.split('='); if (arr[0] == ref){ return url.substr(0, url.indexOf('?')); } else{ return url; } } }27,原生js懒加载
html:<div class="p-list"> <div class="imgs"> <ul id="productlist"> <li class="border-right"> <a href=""> <span class="imgs"> <span class="lazy"> <span class="go-city"> <i class="iconfont icon-dingwei"></i> <b class="city">上海出发</b> <b class="how">邮轮</b> </span> <img data-original="https://r03.uzaicdn.com/content/hybrid/images/search/p9.jpg" src="https://r03.uzaicdn.com/content/hybrid/images/search/head-bg-default.png" alt="" class="lazys" onerror="mySheleves.errorImg(this)"> </span> <h2><【品质济首】韩国首尔+济州岛4晚5日>全程安排五花特<【品质济首】韩国首尔+济州岛4晚5日>全程安排五花特</h2> <span class="price"> <b class="left">¥8888<i>起</i></b> <del>¥9999</del> </span> <span class="label"> <b class="reduce">减</b> <b class="self-support">自营</b> <b class="recommend">推荐</b> <b class="the-first">首发</b> <b class="hot">热卖</b> <b class="all">全包</b> <b class="vip">会员</b> <b class="custom">定制</b> </span> <span class="schedule"> <i class="iconfont icon-calendar"></i> <b class=""> 班期: <em>5/6,7/9,12/12</em> </b> </span> <span class="praise"> <i class="iconfont icon-pingjia"></i> <b> <em>666+人出游</em> <em class="pingjia">好评率100%</em> </b> </span> </span> </a> </li> </ul> </div></div>js:var _imgs = $doc.getElementById('productlist'); //var _img = document.getElementsByClassName('lazys'); //for (var i = 0; i < _img.length; i++) { // if ((_img[i].offsetTop < (window.innerHeight + document.body.scrollTop)) && (_img[i].getAttribute('data-original'))) { // var src_ = _img[i].getAttribute('data-original'); // _img[i].setAttribute('src', src_); // _img[i].removeAttribute('data-original'); // } // //} //console.log(_imgs[0].offsetTop); if($doc.getElementById('productlist')){ var _li = _imgs.getElementsByTagName('li'); var _img, _src; for(var i = 0,len = _li.length;i<len;i++){ _img = _li[i].getElementsByClassName('lazys')[0]; if ((_li[i].offsetTop < (window.innerHeight + document.body.scrollTop)) && (_img.getAttribute('data-original'))){ _src = _img.getAttribute('data-original'); _img.setAttribute('src', _src); _img.removeAttribute('data-original'); } } }28,原生js处理input框第一个不能为空格
var _inputValue = $doc.getElementsByClassName('serchinput')[0].value; //console.log(_inputValue.substr(0,1)); if(_inputValue.substr(0,1) === ' '){ $doc.getElementsByClassName('serchinput')[0].value = _inputValue.replace(/^ +| +$/g,''); }29,删除字符串最后一个字符
substring(0,_inner.length-1);