JavaScript 常用实用函数代码库详解
作者:异步漫步时间:2026-10-28 01:25:45浏览:249
本文整理了一系列 JavaScript 实用函数,涵盖网页收藏、设为首页、可拖拽弹窗、表单数据序列化、错误处理、动态宽度控制、文字滚动、冒泡排序及邮箱格式校验等功能。代码兼容多浏览器,提供完整实现逻辑与参数说明,适用于前端开发中的常见交互场景。
代码如下:
网页收藏与设为首页功能function addBookMark(url, title){
// 将网页添加到收藏夹,调用示例:addBookMark(window.location, document.title)
if(document.all){
window.external.addFavorite(url, title);
}else if (window.sidebar){
window.sidebar.addPanel(title, url, '');
}else{
alert('添加失败');
}
}
function setHomepage(obj, url) {\n// 设置首页,调用示例:setHome(this, window.location)\n try { \n obj.style.behavior = 'url(#default#homepage)'; \n obj.setHomePage(url); \n } catch (e) { \n if (window.netscape) { \n try { \n netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); \n } catch (e) { \n alert('此操作被浏览器拒绝!\\n请在浏览器地址栏输入"about:config"并回车\\n然后将 [signed.applets.codebase_principal_support]的值设置为"true",双击即可。'); \n } \n var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); \n prefs.setCharPref('browser.startup.homepage', vrl); \n } \n }
可拖拽弹窗与遮罩层实现function boxMove(box){\n// 实现可移动的层\n var w = box.scrollWidth, h = box.scrollHeight;\n var iWidth = document.documentElement.clientWidth; \n var iHeight = document.documentElement.clientHeight; \n var moveX = 0, moveY = 0, moveTop = 0, moveLeft = 0, moveable = false;\n box.onmousedown = function(e){ \n moveable = true; \n e = window.event?window.event:e;\n moveX = e.clientX - box.offsetLeft; \n moveY = e.clientY - box.offsetTop;\n box.style.zIndex++;\n }\n document.onmousemove = function(e){\n if(moveable){\n e = window.event?window.event:e; \n var x = e.clientX - moveX;\n var y = e.clientY - moveY;\n if ( x > 0 &&( x + w < iWidth) && y > 0 && (y + h < iHeight)){\n box.style.left = x + "px";\n box.style.top = y + "px";\n box.style.margin = "auto";\n }\n }\n }\n document.onmouseup = function (){moveable = false;};\n}
function getHtmlRoot(){\n/* 获取 HTML 文档的根元素 */\n if(document.compatMode.toLowerCase()=="css1compat"){\n htmlRoot = document.documentElement;\n }else{\n htmlRoot = document.body;\n }\n return htmlRoot;\n}
function showWindow(boxId, closeId, showBg){// 弹窗显示\n htmlRoot = getHtmlRoot();\n box = document.getElementById(boxId);\n boxId = '#' + boxId;\n closeId = '#' + closeId;\n showBox = $(boxId);\n showBox.show();\n z_index = 20;\n moveLeft = (htmlRoot.clientWidth - box.clientWidth)/2 + htmlRoot.scrollLeft +'px';\n moveTop = (htmlRoot.clientHeight - box.clientHeight)/2 + htmlRoot.scrollTop;+'px';\n showBox.css({position:'absolute', left:moveLeft, zIndex:z_index, top:moveTop});
boxMove(box);\n\n if(showBg){\n objMask = document.createElement("div");\n objMask.className = "BoxMask";\n htmlRoot.appendChild(objMask);\n objMask.style.cssText += 'position:absolute;top:0; left:0;filter:Alpha(Opacity=50);opacity:0.5;background:#AAA;';\n\n objMask.style.zIndex = z_index -1;\n objMask.style.width = htmlRoot.clientWidth + 'px';\n objMask.style.height = htmlRoot.scrollHeight + htmlRoot.scrollTop + 'px';\n }\n\n $(closeId).click(function(){\n showBox.hide();\n mybg.style.display = "none";\n });\n $('.closeBtn').click = function(){\n showBox.hide();\n mybg.style.display = "none"; \n };
}
表单数据处理与错误监控function getFormQuery(formId){\n/* 生成查询字符串 */\n formObj = document.getElementById(formId);\n var i, queryString = "", and = "", itemValue;\n for(i = 0; i<formObj.length; i++ ){\n var item = formObj[i];\n if ( item.name!='' ){\n if(item.type == 'select-one'){\n itemValue = item.options[item.selectedIndex].value;\n }else if ( item.type=='checkbox' || item.type=='radio'){\n if ( item.checked == false ){ continue; }\n itemValue = item.value;\n }else if ( item.type == 'button' || item.type == 'submit' || item.type == 'reset' || item.type == 'image'){\n continue;\n }else{\n itemValue = item.value;\n }\n // itemValue = escape(itemValue);\n queryString += and + item.name + '=' + itemValue;\n and="&";\n //queryString += and + encodeURIComponent(item.name) + '=' +encodeURIComponent( itemValue); \n }\n }\n return queryString;\n}
// 定义 JavaScript 错误处理函数\nonerror = errHandle;\nfunction errHandle(msg, url, line){\n var txt=""\n txt = "本页中有错误!\\n\\n"\n txt += "错误: " + msg +"\\n"\n txt += "地址: " + url + "\\n"\n txt += "行数: " + line + "\\n\\n"\n alert(txt);\n return false;\n}
界面元素控制与排序算法function setAutoWidth(id, width, size){\n// 设置最小或最大宽度\n var obj = document.getElementById(id);\n if(size=='max'){\n obj.style.width = (obj.clientWidth > width) ? width + "px" : "auto";\n }else{\n obj.style.width = (obj.clientWidth < width) ? width + "px" : "auto";\n }\n}
function fontScroll(id){\n/* 向左滚动的文字 */\n var obj = document.getElementById(id);\n var text = obj.innerHTML;\n var first = text.charAt(0);\n var left = text.substring(1, text.length);\n obj.inerHTML = left + first;\n // 此函数需在外部通过 setInterval('fontScroll(id)', 500); 调用\n}
function bubbleSort(arr){\n/* 冒泡排序法 */\nvar sign = false // 初始化换位标记为假\nfor(var i=0; i < arr.length-1; i++){\n for(varj=0; j < arr.length-1-i; j++){\n if(arr[j]> arr[j+1]){\n vartemp = arr[j]\n arr[j]= arr[j+1]\n arr[j+1]= temp\n sign= true // 若当前这一圈比较中,有过换位,则置换位标记为真\n }\n }\n if(sign)// 判断当前这一圈有过换位否…\n sign= false // 有过换位,则重置换位标记为假\n else\n break// 没有,则终止\n }\nreturn arr;\n}
坐标获取与邮箱格式校验function getCoordinate(evt){\n/* 获取光标坐标 */\n var x = evt.clientX;\n var y = evt.clientY;\n document.getElementById('show').innerHTML = x +' &' + y;\n}
function checkEmail(email){\n/* 检测多个以分号(;)分隔的Email格式 */\nif(email != null){\n if(email.indexOf(";",0) == -1){ // indexOf(被查找,起始位)返回某个字符串在源字符串中首次出现的位置,失败返回-1\n if(!isEmail(email)){\n alert("单个邮件格式有误,请重输!");\n document.getElementById("email").focus();\n return false;\n }\n }else{\n var emailArr = email.split(";");// split(分隔段,数组总长度)字符串分割成字符串数组\n var i, iMax = emailArr.length;\n for(i = 0; i < iMax; i++){\n if(emailArr[i] != null || emailArr != ""){\n if(!isEmail(emailArr[i])){\n alert("多个邮箱格式中有邮箱格式不正确,请重新核对后再输入!"); \n document.getElementById("email").focus();\n return false;\n }\n }\n }\n } \n}\nfunction isEmail(str){\n var reg = /^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$/;\n return reg.test(str);// test(被测字串)检测一个字符串是否匹配某个模式.\n}\n}作者最新文章
D3.js 比例尺与坐标轴的配置详解
2026-11-05 16:54:46
JavaScript怎么遍历对象的Symbol键和不可枚举属性
2026-11-05 13:13:39
封装一个健壮的JS字符串判空工具函数
2026-11-05 12:16:14
JavaScript合并数组的三种常用方法:concat、扩展运算符与push
2026-11-05 11:22:29
JavaScript立即执行函数(IIFE)是什么及基本语法
2026-11-05 10:51:19
