js事件技巧方法整合

时间:2023-03-09 16:23:16
js事件技巧方法整合
window.resizeTo(800,600); //js设置浏览器窗口尺寸 window.open
(function(){
resizeTo(640,480);//设置浏览器窗口尺寸
moveTo(0,0);//设置浏览器位置
})() screen.availHeight;//显示屏最高高度
screen.availWidth;//显示屏最宽宽度 /*窗口改变大小 事件*/
//js
window.onresize = function()
{
if(resizeTimer==null)
{
resizeTimer = setTimeout("doResize()",300);
}
}
//jquery
$(window).resize(function () {
setTimeout(function () {
var w = $(window).width();
var h = $(window).height(); $('.divLeft').animate({ height: h - 60 }, 500)
$('.divRight').animate({ width: w - 189, height: h - 90 }, 500);
}, 1);
})
/*checkbox 选择、取消 (筛选加入多个元素)*/
$("#radyixiaofei_ctl01 tbody tr").add($("#RadGrid1_ctl01 tbody tr")).on("click", function () {
$(this).find(":checkbox").attr("checked", function () { return !$(this).attr("checked") })
});
 //取消浏览器的所有事件,使得active的样式在手机上正常生效
document.addEventListener("touchstart", function (e) {
return false;
}, true);
//向上滚动
function BeatAll(id) {
var container = document.getElementById(id);
try {
container.appendChild(container.firstChild);
}
catch (e) { }
}
//向下滚动
function BeatAllDown(id) {
$("#" + id).prepend($("#" + id).children().last());
}
//setInterval("BeatAll(List0)", 10000);
var jsOpts = {
//Select根据text选中 param
setSelectDefualtValue: function (optionID, val) {
$("#" + optionID + ">option").each(function () {
var txtOption = $(this).text();
if (txtOption.indexOf(val) > -1) {
$(this).attr("selected", "selected");
return false;
}
});
},
//input select初始化
setDefualt: function (id) {
$("input[type='text']", $("#" + id)).val("");
$("select", $("#" + id)).each(function () {
$(this).children("option:first").attr("selected", true);
});
},
//input text 聚焦失焦效果
focusEffect: function (obj) {
//初始化
$(obj).val($(obj).attr("title"));
$(obj).css("color", "#777"); $(obj).focus(function () {
if ($(obj).val() == $(obj).attr("title")) {
$(obj).val("");
}
else {
$(obj).select();
}
$(obj).css("color", "#000");
});
$(obj).blur(function () {
if ($(obj).val() == "") {
$(obj).val($(obj).attr("title"));
$(obj).css("color", "#777");
}
});
},
//checkbox全、反选
checkFormAll: function (id, val) {
$("#" + id).find("input[type='checkbox']").attr("checked", val);
}
}
//计算每个字符出现的次数
var t = "stringthatresults", i = 0, len = t.length,
result = [],//输出结果
hash = {};//hash表,用于记录是否重复计算字符
for (i = 0; i < len; i++) {
if (!hash[t.charAt(i)]) {
hash[t.charAt(i)] = true;
//分割当前字符本身,来获取出现次数
result.push(t.charAt(i) + ":" + (t.split(t.charAt(i)).length - 1));
}
}
document.writeln(JSON.stringify(result) + "<br />"); result = [];
var count = 0, tmp = "", arr = t.split("");
for (i = 0; i < len; i++) { //替换当前字符,再通过与原有字符串长度做加减,来获取出现次数
tmp = t.replace(new RegExp(arr[i], "g"), "");
count = t.length - tmp.length; if (count > 0) {
result.push(arr[i] + ":" + count);
}
t = tmp;
}
document.writeln(JSON.stringify(result)); //结果
["s:3","t:4","r:2","i:1","n:1","g:1","h:1","a:1","e:1","u:1","l:1"]
["s:3","t:4","r:2","i:1","n:1","g:1","h:1","a:1","e:1","u:1","l:1"]
var a = "stringthatresults";
var b = {};
var c = null;
for (var i in a) {
if (!isNaN(b[a[i]]++) || (b[a[i]] = 1)) {
c = b[a[i]] > c ? a[i] : c;
}
}
document.writeln(JSON.stringify(b));
//点击tr选中checkbox
$("#idTable1 tbody tr").click(function () {
var obj = $(this).find("input[type='checkbox']").first();
$(obj).attr("checked", !$(obj).attr("checked"));
}).find("input[type='checkbox']").click(function (event) {
event.stopPropagation();
//return false;
})
 

js中的preventDefault和stopPropagation_阻止事件

<title>JS阻止链接跳转</title>
<script type="text/javascript">
function stopDefault( e ) {
if ( e && e.preventDefault )
e.preventDefault();
else
window.event.returnValue = false; return false;
}
</script>
</head>
<body>
<a href="http://www.baidu.com" id="testLink">百度</a>
<script type="text/javascript">
var test = document.getElementById('testLink');
test.onclick = function(e) {
alert('我的链接地址是:' + this.href + ', 但是我不会跳转。');
stopDefault(e);
}
</script>
<title> 阻止JS事件冒泡传递(cancelBubble 、stopPropagation)</title>
<meta name="keywords" content="JS,事件冒泡,cancelBubble,stopPropagation" />
<script>
function doSomething (obj,evt) {
alert(obj.id);
var e=(evt)?evt:window.event;
if (window.event) {
e.cancelBubble=true; // ie下阻止冒泡
} else {
//e.preventDefault();
e.stopPropagation(); // 其它浏览器下阻止冒泡
}
}
</script>

加载JS方法:

//加载JS
function loadJsByUrl(url) {
var head = document.getElementsByTagName('HEAD').item(0);
var js = document.createElement("script");
js.type = "text/javascript";
js.src = url;
head.appendChild(js);
//var s = document.getElementsByTagName("script")[0];
//s.parentNode.insertBefore(hm, s);
} //加载JS并回调带参数的方法
function loadadByUrl(url, gpuri, imguri, fun) {
var head = document.getElementsByTagName('HEAD').item(0);
var js = document.createElement("script");
js.type = "text/javascript";
js.src = url;
head.appendChild(js);
var d = setInterval(function () {
if (eval(fun) != 'defined') {
eval(fun + '(\'' + gpuri + '\',\'' + imguri + '\')');
clearInterval(d);
}
}, 500)
}
//获取url参数
function RequestFrom(key) {
var locString = location.search;
var reg = new RegExp("(\\?|\\&)" + key + "=([^\\&]*)(\\&?)", "i").exec(locString);
if (reg != null) {
return RegExp.$2;
}
else {
return "";
}
} String.prototype.replaceAll = function (val, Reg) {
return this.replace(new RegExp(val, "gm"), Reg);
}
//post提交
function httpPost(url, params, target) {
var tempform = document.createElement("form");
tempform.action = url;
tempform.method = "post";
tempform.style.display = "none"
if (target) {
tempform.target = target;
} for (var x in params) {
var opt = document.createElement("input");
opt.name = x;
opt.value = params[x];
tempform.appendChild(opt);
} var opt = document.createElement("input");
opt.type = "submit";
tempform.appendChild(opt);
document.body.appendChild(tempform);
tempform.submit();
document.body.removeChild(tempform);
}

字符串扩展方法:

String.prototype.replaceAll = function (val, Reg) {
return this.replace(new RegExp(val, "gm"), Reg);
} String.prototype.Trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function () {
return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function () {
return this.replace(/(\s*$)/g, "");
} //进行四舍五入
Number.prototype.toFx = function () {
var x = this;
var f_x = parseFloat(x);
if (isNaN(f_x)) {
alert('输入不正确,请输入正确的阿拉伯数字');
return false;
}
f_x = Math.round(x * 100) / 100;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + 2) {
s_x += '0';
}
return s_x;
}
//Float小数位修约
Math.formatFloat = function (f, digit) {
var m = Math.pow(10, digit);
return Math.round(f * m, 10) / m;
}
//间隔插入字符
String.prototype.IntervalInsert = function (i, str) {
var ma = this.toString().match(new RegExp("\.{1," + i + "}", "g"));;
return ma.join(str);
}
//自定义字典对象 JS Dictionary
// 自定义字典对象
function Dictionary() {
this.keys = new Array();
//添加键值对
this.set = function (key, value) {
if ($.inArray(key, this.keys) < 0) {//如键不存在则身【键】数组添加键名
this.keys.push(key);
}
}; this.existencekey = function (key) {
var index = $.inArray(key, this.keys);
return index >= 0 ? true : false;
}
//获取键对应的值
//this.get = function (key) {
// return this.data[key];
//};
//移除
this.remove = function (key) {
this.keys.splice($.inArray(key, this.keys), 1);
};
//判断键值元素是否为空
this.isEmpty = function () {
return this.keys.length == 0;
};
//获取键值元素大小
this.size = function () {
return this.keys.length;
};
}
/*js脚本文件延迟置后执行*/
//[defer]
<script defer="true"></script>
//告诉浏览器这段script不必立即执行,那么浏览器就会在完全载入文档之后再执行这个script,相当于window.onload,但它比window.onload更灵活。 //[async]
<scriptasync="true"></script>
//告诉浏览器该脚本不会在页面加载完成之前操作DOM,脚本将会和其他资源文件并行下载; HTML5新的异步、并行模式,脚本将在完成下载后等待合适的时机执行代码
/*框架中多级嵌套—调用方法*/
//js
window.top.document.getElementById("mainframe").contentDocument.getElementById("frameContent").contentWindow.fc(); //jquery
$(window.top.document.getElementById("mainframe")).contents().find("#frameContent")[0].contentWindow.fc(); //contentWindow 兼容各个浏览器,可取得子窗口的 window 对象。 //contentDocument Firefox、谷歌 支持,> ie8 的ie支持等。可取得子窗口的 document 对象。
//js日期格式化
Date.prototype.format = function (format) {
var o =
{
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //day
"h+": this.getHours(), //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() //millisecond
}
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
return format;
} var dt=Dtime.format("yyyy-MM-dd hh:mm:ss")
        /*基于JS判断iframe是否加载成功的方法(多种浏览器)*/
if (iframe.attachEvent) {
iframe.attachEvent("onreadystatechange", function () {
//此事件在内容没有被载入时候也会被触发,所以我们要判断状态
//有时候会比较怪异 readyState状态会跳过 complete 所以我们loaded状态也要判断
if (iframe.readyState === "complete" || iframe.readyState == "loaded") {
//代码能执行到这里说明已经载入成功完毕了
//要清除掉事件
iframe.detachEvent("onreadystatechange", arguments.callee);
//这里是回调函数
}
});
} else {
iframe.addEventListener("load", function () {
//代码能执行到这里说明已经载入成功完毕了
this.removeEventListener("load", arguments.call, false);
//这里是回调函数
}, false);
}
/*WdatePicker日历控件多种日期格式切换*/
function setDateInput(vt) {
var $tp_ST = $("#txtSTime");
var $tp_ET = $("#txtETime"); var $ST = $tp_ST.clone(false);
var $ET = $tp_ET.clone(false);
$tp_ST.parent().empty().append($ST);
$tp_ET.parent().empty().append($ET); if (vt == 0) {
$ST.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM-dd HH:00', maxDate: '#F{$dp.$D(\'txtETime\')}' });
});
$ET.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM-dd HH:00', maxDate: '%y-%M', minDate: '#F{$dp.$D(\'txtSTime\')}' });
}); var startdate = new Date();
$ET.val(utils.formatDate(startdate, "yyyy-MM-dd hh:00"));
startdate.setHours(startdate.getHours() - 4);
$ST.val(utils.formatDate(startdate, "yyyy-MM-dd hh:00"));
}
else if (vt == 1) {
$ST.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM-dd', maxDate: '#F{$dp.$D(\'txtETime\')}' });
});
$ET.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM-dd', maxDate: '%y-%M-%d', minDate: '#F{$dp.$D(\'txtSTime\')}' });
}); var startdate = new Date();
startdate.setDate(startdate.getDate() - 1);
$ST.val(utils.formatDate(startdate, "yyyy-MM-dd"));
$ET.val(utils.formatDate(startdate, "yyyy-MM-dd"));
} else if (vt == 2) {
$ST.click(function () {
WdatePicker({ isShowWeek: true, onpicked: GetWeek1, firstDayOfWeek: 1, errDealMode: 3, isShowClear: false })
});
$ET.click(function () {
WdatePicker({ isShowWeek: true, onpicked: GetWeek2, firstDayOfWeek: 1, errDealMode: 3, isShowClear: false })
});
} else if (vt == 3) {
$ST.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM', maxDate: '#F{$dp.$D(\'txtETime\')}' });
});
$ET.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM', maxDate: '%y-%M', minDate: '#F{$dp.$D(\'txtSTime\')}' });
}); var startdate = new Date();
startdate.setMonth(startdate.getMonth() - 1);
//时间多月
$ST.val(utils.formatDate(startdate, 'yyyy-MM'));
$ET.val(utils.formatDate(startdate, 'yyyy-MM'));
}
else if (vt == 4) {
$ST.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM季', isQuarter: true, isShowOK: false, disabledDates: ['....-0[5-9]-..', '....-1[0-2]-..'], startDate: '%y-01-01' });
});
$ET.click(function () {
WdatePicker({ dateFmt: 'yyyy-MM季', isQuarter: true, isShowOK: false, disabledDates: ['....-0[5-9]-..', '....-1[0-2]-..'], startDate: '%y-01-01' });
});
}
else if (vt == 5) {
$ST.click(function () {
WdatePicker({ dateFmt: 'yyyy' });
});
$ET.click(function () {
WdatePicker({ dateFmt: 'yyyy' });
});
}
}
function GetWeek1() {
$dp.$('txtSTime').value = $dp.cal.getP('y') + "-" + $dp.cal.getP('W', 'WW') + "周";
$("#hdSTime").val($dp.cal.getP('y') + "-" + $dp.cal.getP('M') + "-" + $dp.cal.getP('d'));
}
function GetWeek2() {
$dp.$('txtETime').value = $dp.cal.getP('y') + "-" + $dp.cal.getP('W', 'WW') + "周";
$("#hdETime").val($dp.cal.getP('y') + "-" + $dp.cal.getP('M') + "-" + $dp.cal.getP('d'));
}

未写完……