js事件技巧方法整合
生活随笔
收集整理的這篇文章主要介紹了
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選中 paramsetSelectDefualtValue: 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腳本文件延遲置后執行*/ //[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);}?
?
未寫完……
轉載于:https://www.cnblogs.com/elves/p/3738151.html
總結
以上是生活随笔為你收集整理的js事件技巧方法整合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IOS问题汇总:2015-1-14 xi
- 下一篇: echart封装,前端简单路由,图表设置