jquery项⽬中⼀些常⽤⽅法
1、获取url中的参数
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); //构造⼀个含有⽬标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配⽬标参数以及解析中⽂乱码问题
if (r != null) return decodeURI(r[2]); return null; //返回参数值
}
调⽤:getUrlParam(参数名称) 注意:参数名称是⼀个字符串
2、封装ajax加移动端当数据没出现出现加载图标
//封装ajax请求、
function ajax_datatypeByXml(type, url, Xml_data, func) {//data数据可以为空
$.ajax({
type: type,
url: url,
async: false,
dataType: "json",
timeout: 30000, //超时时间:30秒
data: Xml_data,
beforeSend: function () {
mui.showLoading("正在加载..", "div"); //加载⽂字和类型,plus环境中类型为div时强制以div⽅式显⽰ },
complete: function () {
mui.hideLoading(function () {
});//隐藏后的回调函数
},
success: function (data) {
if (data) {
func(data);
} else {
mui.alert("数据加载失败");
}
},
error: function() {
mui.alert('服务器连接超时,请稍后再试');
}
});
}
//扩展mui.showLoading
(function ($, window) {
//显⽰加载框
$.showLoading = function (message, type) {
if ($.os.plus && type !== 'div') {
$.plusReady(function () {
plus.nativeUI.showWaiting(message);
});
} else {
var html = '';
html += '<i class="mui-spinner mui-spinner-white"></i>';
html += '<p class="text">' + (message || "数据加载中") + '</p>';
//遮罩层
var mask = ElementsByClassName("mui-show-loading-mask");
if (mask.length == 0) {
mask = ateElement('div');
mask.classList.add("mui-show-loading-mask");
document.body.appendChild(mask);
mask.addEventListener("touchmove", function (e) { e.stopPropagation(); e.preventDefault(); });
} else {
mask[0].ve("mui-show-loading-mask-hidden");
}
//加载框
var toast = ElementsByClassName("mui-show-loading");
if (toast.length == 0) {
toast = ateElement('div');
toast.classList.add("mui-show-loading");
toast.classList.add('loading-visible');
document.body.appendChild(toast);
toast.innerHTML = html;
toast.addEventListener("touchmove", function (e) { e.stopPropagation(); e.preventDefault(); }); } else {
toast[0].innerHTML = html;
toast[0].classList.add("loading-visible");
}
jquery在项目里是干啥的}
};
//隐藏加载框
$.hideLoading = function (callback) {
if ($.os.plus) {
$.plusReady(function () {
plus.nativeUI.closeWaiting();
});
}
var mask = ElementsByClassName("mui-show-loading-mask");
var toast = ElementsByClassName("mui-show-loading");
if (mask.length > 0) {
mask[0].classList.add("mui-show-loading-mask-hidden");
}
if (toast.length > 0) {
toast[0].ve("loading-visible");
callback && callback();
}
}
})(mui, window);
3、初始化移动端根节点字体⼤⼩⽤作rem值
window.addEventListener("resize", setSize, false);
window.addEventListener("orientationchange", setSize, false);
function setSize() {
var oHtml = ElementsByTagName("html")[0];
var iWidth = BoundingClientRect().width;
$("html").css("fontSize", iWidth / 15)
}
4、根据年⽉获得当⽉天数的实现代码
function getDaysInMonth(year, month) {
month = parseInt(month, 10);
var temp = new Date(year, month, 0);
Date();
}
5、屏蔽打印console
console.log=function(){}
6、当动态⽣成li时点击事件有时可能会触发两次解决办法
$('body').off('click').on('click','selector',function(){});
使⽤之前要清理掉body上绑定的click事件,利⽤了jQuery⾥⾯off()⽅法
7、选择input框的选中状态操作
<div class="desc">
<input type="checkbox" id="selectAll" onclick="checkAll()">全选
</div>
<script>
function checkAll()
{
var checkedOfAll=$("#selectAll").prop("checked");
$("input[name='procheck']").prop("checked", checkedOfAll);
alert(checkedOfAll);
}
</script>
8、⿏标移⼊移出事件并在移⼊时操作
$(".contactus-wrap").mouseover( function () {
clearTimeout(time);
$(".contactus").css({
"opacity": 1,
"left":"12px"
})
});
$(".contactus-wrap").mouseout(
function () {
time = setTimeout(function () {
$(".contactus").css({
"opacity": 0,
"left": "-206px"
})
}, 500)
});
$(".contactus").mouseover(function () {
clearTimeout(time); $(".contactus").css({
"opacity": 1,
"left": "12px"
})
});
$(".contactus").mouseout(function () {
time = setTimeout(function () {
$(".contactus").css({
"opacity": 0,
"left": "-206px"
})
}, 500);
});
9、jquery中获取⽗级iframe中的dom元素
$(parent.window.document).find("iframe").contents().find("#F_HTNO");10、textarea⾃动换⾏,且⽂本框根据输⼊内容⾃适应⾼度<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>输⼊框⾃适应</title>
<script src="jquery.min.js"></script>
<script>
// textare⾃动换⾏
/**
* ⽂本框根据输⼊内容⾃适应⾼度
* @param {HTMLElement} 输⼊框元素
* @param {Number} 设置光标与输⼊框保持的距离(默认0)
* @param {Number} 设置最⼤⾼度(可选)
*/
var autoTextarea = function (elem, extra, maxHeight) {
extra = extra || 0;
var isFirefox = !!BoxObjectFor || 'mozInnerScreenX' in window,
isOpera = !!window.opera && !!String().indexOf('Opera'),
addEvent = function (type, callback) {
elem.addEventListener ?
elem.addEventListener(type, callback, false) :
elem.attachEvent('on' + type, callback);
},
getStyle = elem.currentStyle ? function (name) {
var val = elem.currentStyle[name];
if (name === 'height' && val.search(/px/i) !== 1) {
var rect = BoundingClientRect();
return rect.bottom - p -
parseFloat(getStyle('paddingTop')) -
parseFloat(getStyle('paddingBottom')) + 'px';
};
return val;
} : function (name) {
return getComputedStyle(elem, null)[name];
},
minHeight = parseFloat(getStyle('height'));
size = 'none';
var change = function () {
var scrollTop, height,
padding = 0,
style = elem.style;
if (elem._length === elem.value.length) return;
elem._length = elem.value.length;
if (!isFirefox && !isOpera) {
padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
};
scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
elem.style.height = minHeight + 'px';
if (elem.scrollHeight > minHeight) {
if (maxHeight && elem.scrollHeight > maxHeight) {
height = maxHeight;
style.overflowY = 'auto';
} else {
height = elem.scrollHeight;
style.overflowY = 'hidden';
};
style.height = height + extra + 'px';
// scrollTop += parseInt(style.height) - elem.currHeight;
// document.body.scrollTop = scrollTop;
// document.documentElement.scrollTop = scrollTop;
elem.currHeight = parseInt(style.height);
};
};
addEvent('propertychange', change);
addEvent('input', change);
addEvent('focus', change);
change();
};
$(document).ready(function() {
$("table td").each(function() {
if ($(this).find("[datatype='required']").length > 0||$(this).find("[datatype='number']").length > 0) {
$(this).css("position", "relative");
}
})
})
</script>
</head>
<body>
<table>
<tr>
<td>
<textarea datatype="required" id="grxygzjh"
isheightauto="true" maxlength="1000"
msg="必填项" name="grxygzjh" onfocus="autoTextarea(this)"
placeholder="*请输⼊个⼈下⽉⼯作计划"
type="text">
</textarea></td>
</tr>
</table>
</body>
</html>
11、移动端悬浮按钮可拖动
touchImg: function () {
var flag = 0; //标记是拖曳还是点击
var oDiv = ElementsByClassName('add-btn')[0];
var disX,moveX,L,T,starX,starY,starXEnd,starYEnd;
oDiv.addEventListener('touchstart',function(e){
flag = 0;
e.preventDefault();//阻⽌触摸时页⾯的滚动,缩放
disX = e.touches[0].clientX - this.offsetLeft;
disY = e.touches[0].clientY - this.offsetTop;
//⼿指按下时的坐标
starX = e.touches[0].clientX;
starY = e.touches[0].clientY;
//console.log(disX);
});
oDiv.addEventListener('touchmove',function(e){
flag = 1;
L = e.touches[0].clientX - disX ;
T = e.touches[0].clientY - disY ;
//移动时当前位置与起始位置之间的差值
starXEnd = e.touches[0].clientX - starX;
starYEnd = e.touches[0].clientY - starY;
//console.log(L);
if(L<0){//限制拖拽的X范围,不能拖出屏幕
L = 0;
}else if(L > document.documentElement.clientWidth - this.offsetWidth){
L=document.documentElement.clientWidth - this.offsetWidth;
}
if(T<0){//限制拖拽的Y范围,不能拖出屏幕
T=0;
}else if(T>document.documentElement.clientHeight - this.offsetHeight){
T = document.documentElement.clientHeight - this.offsetHeight;
console.log(T)
}
moveX = L + 'px';
moveY = T + 'px';
//console.log(moveX);
this.style.left = moveX;
p = moveY;
});
window.addEventListener('touchend',function(e){
//alert(parseInt(moveX))
//判断滑动⽅向
if(flag === 0) {//点击
}
});
}
}
12、监听input中value改变
//监听input中value改变
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;//浏览器兼容var config = { attributes: true, childList: true }//配置对象
$("input").each(function () {
var _this = $(this);
var observer = new MutationObserver(function (mutations) {//构造函数回调
mutations.forEach(function (record) {
if (pe == "attributes") {//监听属性
load();
}
if (pe == 'childList') {//监听结构发⽣变化
//do any code
}
});
});
observer.observe(_this[0], config);
});
13、监听多张图⽚加载完成
$.when.apply(null, $(".ccc").map(function(i, e) {
var dfd = $.Deferred();
if (eplete) {
console.log(`${i}`)
} else {
console.log(`${i}`)
}
}
return dfd;
}).toArray()).done(function() {
console.log("图⽚加载完成");
//要执⾏的⽅法loop();
});
console.log("图⽚开始加载");
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论