English(beta)
hfyb的Blog 页面正在加载中 .....

常用的JavaScript

装载http://www.cnblogs.com/fubeidong/archive/2007/01/19/624539.html
1. 动态调整select
<select id=test size=3>
<option>选项一</option>
<option>选项二</option>
<option>选项三</option>
</select>

<button onclick="up(test)">向上</button>

<script>
function up(obj)
{
if (obj.selectedIndex>0)
obj.options(obj.selectedIndex).swapNode(obj.options(obj.selectedIndex-1))
}
</script>

2. 实现select的细线边框
<span style="border:1px solid #000000; position:absolute; overflow:hidden"><select style="margin:-2px">
<option>1111</option>
<option>11111111111111</option>
<option>111111111</option>
</select></span>

3. 弹出窗口自动适应大小
<script>
function autoResize(src)
{
function resizeOpenWin()
{
  var srcElem = event.srcElement
  if (document.resized)  return
  window.setTimeout(function ()
  {
   window.resizeBy(srcElem.width-100, srcElem.height-100)
  },1)
  document.resized = true
}

var newbody = "<body style=margin:0px><script>"+resizeOpenWin.toString()+"</"+"script><img src="+src+" onreadystatechange=resizeOpenWin()></body>"
var newwin = window.open("", "", "width=100, height=100, toolbar=yes")
newwin.document.write(newbody)
newwin.document.close()
}
autoResize("http://www.imagegarden.net/photo/scan/view.php?url=/scan/084/21.jpg")
</script>

4. 捕获关闭按钮
<script>
window.onbeforeunload = function()
{
if (document.body.offsetWidth-50 < event.clientX && event.clientY<0)
return "是否关闭当前窗口"
}
</script>

5. 判断链接是否被访问
<style>
a {visited:false}
a:visited {visited:true}
</style>

<a href="###" onclick="alert(event.srcElement.currentStyle.visited);return false">link1</a>
<a href="abcd" onclick="alert(event.srcElement.currentStyle.visited);return false">link2</a>

6. expression 妙用
<script>
function test()
{
alert("expression function")
}
</script>

<style>
a {qiushuiwuhen:expression(this.onclick=test)}
</style>

<a href="javascript:;">expression</a>

7. 多彩链接
<style>
span {color: #FF6600}
a {color: #9299A6}
</style>

<a href="javascript:;"><span>link</span></a>

8. iframe 自动适应大小
<script>
function autoResize()
{
try
{
  document.all["test"].style.height=test.document.body.scrollHeight
}
catch(e){}
}
</script>

<iframe id=test style="height:expression(1); aho:expression(autoResize())" src="\">

9. 用onmouseover、onmouseout 实现 onmouseenter 和 onmouseleave

onmouseover  = if (!this.contains(event.fromElement)) {...}onmouseout   = if (!this.contains(event.toElement)) {...}


10. 中文两端对齐
<DIV style="text-align:justify; text-justify:Distribute-all-lines;">搜易论坛搜易论坛</DIV>


11. 生成连续字符
<script>
alert(new Array(10).join("a"))
</script>

12. 强制图片载入

<img onerror="this.src=this.src" ...


13. 获取色盘颜色
<body>
<span style="background-color:buttonface" id=demo>buttonface</span>

<script>
var rng = document.body.createTextRange();
rng.moveToElementText(demo)
var bColor=rng.queryCommandValue("BackColor");
str=("000000"+bColor.toString(16)).match(/.{6}$/)
alert("#"+str.slice(-2)+str.slice(2,-2)+str.slice(2))
</script>
</body>

14. 不进行转义的字符串
<script>alert (/\n\r\t/.source)</script>

15. 判断日期是否合法
<script>
function isDate(strDate)
{
  if (!strDate) return false
  var date1 = new Array()
  var date2 = null
  
  try
  {
   date1[0] = strDate.match(/\d{4}/)
   strDate  = strDate.replace(date1[0],"")
   date1[1] = parseInt(strDate.match(/\d+/g)[0])+1
   strDate  = strDate.replace(date1[1],"")
   date1[2] = parseInt(strDate.match(/\d+/g))
   date2  = new Date(date1.join("\/"))
   
   return date1.join("\/") == date2.getYear() +"\/"+ (date2.getMonth()+1) +"\/"+ date2.getDate()
  }
  catch(e)
  {
   return false
  }
}

alert(isDate("2003/01/01"))
alert(isDate("01/01/2003"))
alert(isDate("01-01-2003"))
alert(isDate("2003/21/01"))
alert(isDate("2003/01/01 20:00:00"))
</script>

16. 打开我的电脑,控制面板等
<a href="file:///::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" target=_blank>我的电脑</a><br>
<a href="file:///c:/" target=_blank>本地C盘</a><br>
<a href="file:///d:/" target=_blank>本地D盘</a><br>
<a href="file:///c:/" target=_blank>本地E盘</a><br>
<a href="file:///::{208D2C60-3AEA-1069-A2D7-08002B30309D}" target=_blank>网上邻居</a><br>
<a href="file:///::{450D8FBA-AD25-11D0-98A8-0800361B1103}" target=_blank>我的文档</a><br>
<a href="file:///::{20D04FE0-3AEA-1069-A2D8-08002B30309D}/::{21EC2020-3AEA-1069-A2DD-08002B30309D}" target=_blank>控制面板</a><br>
<a href="file:///::{645FF040-5081-101B-9F08-00AA002F954E}" target=_blank>回收站</a><br>

17. 强制转为整型变量
<script>
alert (123|0)
alert (123.456|0)
alert ("abc"|0)
</script>

18. 把0-6的星期表示改为1-7表示的表示方法
<script>
for (var i=0; i<7; i++) alert(Math.ceil((i+7)%7.5))
</script>

19. 判断是否是工作日
<script>
alert(new Date().getDay()%6 ? "工作日" : "双休日")
</script>

20. 去除字符串首尾的空格
<script>
alert("    aaaa             ".replace(/^\s*|\s*$/g, ""))
</script>

21. 获得本月的天数
<script>
alert(new Date(new Date().getYear(), new Date().getMonth()+1, 0).getDate())
</script>

22. 正则不匹配词组
不含"yes"或者"no":<br>
<script>
function d(s){document.write(s+"<br>")}
str=new Array("yes","no","auto","yseauto","sey","esyno");
for(i in str)
d(str[i].bold()+" : "+/^(y(?!es)|n(?!o)|[^yn])*$/.test(str[i]));
</script>

23. 使用模式窗口浏览网页
<script language=JavaScript>
showModalDialog("about:<iframe src=http://www.blueidea.com/bbswidth=100% height=100%></iframe>")
</script>

24. 随机重排数组
<script>
ars=[金,木,水,火,土,仁,义,礼,志,贤]
for (var i=0; i<10; i++)
document.write(ars.sort(function(){return Math.random( )*new Date%3-1})+"<br />")
</script>

25. 自动等分的Table
<style>
tr {
  position: relative;
  top:  expression(-1*this.sectionRowIndex*(offsetHeight-2));
  left:  expression(this.sectionRowIndex*this.offsetWidth);
  height:  100px;
}

td {
  border:  1px solid buttonface;
  font-size: 12px;
}
</style>

<table>
<tbody>
  <tr><td><span CONTENTEDITABLE id="e">1111111</span></td></tr>
  <tr><td><span>222</span></td></tr>
  <tr><td><span>33333</span></td></tr>
  <tr><td><span>4</span></td></tr>
</tbody>

<script>
  otr = document.body.createTextRange()
  otr.moveToElementText(document.all["e"])
  otr.select()
  e.focus()
</script>
</table>

26. 格式化数字
<script>
num = 1
len = 3
alert((new Array(len).join("0")+num).slice(-len))
</script>

27. 获得路径
<script>
function getURL()
{
var allPath  = /^[\\\/]+/.test(filePath.value) ? filePath.value : currentPath.value + filePath.value
var pathArray = allPath.split(/[\\\/]+/)
var tmpArray = new Array

for (var i=0; i<pathArray.length; i++)
{
  switch (pathArray[i])
  {
   case "." :
    break
   case ".." :
    tmpArray.pop()
    break
   default  :
    tmpArray[tmpArray.length] = pathArray[i]
    break
  }
}

alert(tmpArray.join("\/"))
}
</script>
当前路径:<input id="currentPath" value="asp.net/xml/" /><br />
文件路径:<input id="filePath" value="./../w/../fs\r.g///if"/>
<button onclick="getURL()">getURL</button>

28. 清除删除滤镜后仍对Body的影响
<script for=window event=onload>
oldBody = document.body
newBody = document.createElement("BODY")

oldBody.style.filter="blendTrans(duration=1)"
oldBody.applyElement(newBody, "inside")
oldBody.swapNode(newBody)
oldBody.removeNode(true)
</script>

<div style="height: 1000px">
a
</div>

29. 接管alert
<script>
function window.alert(msg)
{
  window.showModalDialog("about:"+msg)
}

alert("我是Alert")
</script>

30. 每次响应select选择
<script>
function change()
{
var src=event.srcElement
if ( !(event.clientX > src.offsetLeft &&
   event.clientX < src.offsetLeft + src.offsetWidth &&
   event.clientY > src.offsetTop &&
   event.clientY < src.offsetTop+src.offsetHeight))
window.status = src.options[src.selectedIndex].text
}
</script>

<select onclick="change()">
<option>aaaaa</option>
<option>bbbbb</option>
<option>ccccc</option>
<option>ddddd</option>
</select>

31. 求出两组日期的相交的日期
<script>
var date1 = ["2003/1/1", "2004/5/6", "1998/1/2"]
var date2 = ["2003/1/1", "2008/12/1"]
var date3 = ["2003/2/2", "2008/12/1"]
var date4 = ["2003/1/1", "2004/5/6"]

function cmDate(d1, d2)
{
return d2.toString().match(new RegExp("("+d1.join("|")+")", "g"))
}

alert(cmDate(date1, date2))
alert(cmDate(date1, date3))
alert(cmDate(date1, date4))
</script>

32. 用图片替换上传文件框
<form action="javascript:alert(上传成功)" method="post" enctype="multipart/form-data">

<div style="position: absolute; top: 15px; filter: alpha(opacity=0); left: -26px;"><input id="upload" type="file" name="upload" size="1" /></div>

<input type="button" value="选择文件" onclick="upload.click()" />
<input type="submit" />
</form>

33. 同时显示多个 popup window
<script>
var popHTML = "<span onclick=var a = document.parentWindow.createPopup();var b = a.document.body;b.innerHTML = top.popHTML;a.show(5, 100, 180, 25, document.body);>popup window</span>"

document.write(popHTML)
</script>

34. 屏蔽快捷键
<script>
document.onkeydown = function()
{
event.keyCode=0
return false
}

document.onhelp = function()
{
return false
}
</script>

35. 正则表达式连接函数
<script for=window event=onload>
function getRelativeReg(reg)
{
  var regStr = reg.source
  var relaStr = regStr.match(/(\\\d+|\\.[^\\]*|[^\\]*)/g)
  
  while (relaStr.length-1)
  {
   if (/^\\\d+$/.test(relaStr[1]))
   {
    relaStr[1] = "\\______rela:" + (parseInt(relaStr[1].match(/\d+/g)) - relaStr[0].match(/\(/g).length) + "______"
   }
   relaStr[0] = relaStr.shift() + relaStr[0]
  }
  
  return relaStr.join("")
}

function getAbsoluteReg(regStr, s)
{
  var absStr = regStr.match(/(\\______rela:-?\d+______|\\.[^\\]*|[^\\]*)/g)
  
  while (absStr.length-1)
  {
   if (/^\\______rela:-?\d+______$/.test(absStr[1]))
   {
    absStr[1] = "\\" + (parseInt(absStr[1].match(/-?\d+/g)) + absStr[0].match(/\(/g).length)
   }
   absStr[0] = absStr.shift() + absStr[0]
  }
  
  return new RegExp(absStr.join(""), s)
}

var re = /\w+(\s*=\s*((["])(\\["tbnr]|[^\3])*?\3|\w+))/ig
alert(re)
alert(getAbsoluteReg("(\\a)" + "(" + getRelativeReg(re) + ")", "ig"))
</script>

36. 文字自适应分辩率
<style>
body, table{font-size: 1em; line-height:180%;}
</style>

<body>
<script>
function bodyFontSize(){
document.body.runtimeStyle.fontSize = 11*Math.pow(screen.width/640, 0.5)
}
bodyFontSize()
setInterval(bodyFontSize, 1000)
</script>

Email 提醒: 如果有回复则通过电子邮件提醒。只有注册用户才有此功能。<br />
禁止笑脸转换:如果您的帖子中有转帖代码,请筛选复选此项。<br />
显示签名: 包含您在户口本中的签名。只有注册用户有此功能。

<table><tr><td>
Email 提醒: 如果有回复则通过电子邮件提醒。只有注册用户才有此功能。<br />
禁止笑脸转换:如果您的帖子中有转帖代码,请筛选复选此项。<br />
显示签名: 包含您在户口本中的签名。只有注册用户有此功能。</table>
</body>

37. 保存远程文件到本地
<script>
function saveServerFile(serverUrl, localPath)
{
  var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
  var adoStream = new ActiveXObject("ADODB.Stream")
  xmlhttp.open("GET", serverUrl, false)
  xmlhttp.send()
  
  adoStream.Type = 1
  adoStream.Mode = 3
  adoStream.Open()
  adoStream.write(xmlhttp.responseBody)
  
  adoStream.SaveToFile(localPath, 2)
}

saveServerFile("/bbs/images/topic5.gif", prompt("输入文件保存路径", "c:\\\\test.gif"))
</script>

38. 表格图片自动缩放
<!--[if gte IE 5.5]>
<style>
img {zoom:expression(Math.min(this.parentElement.offsetWidth/this.width,1))}
table.bbsBody {table-layout:fixed; word-wrap: break-word}
</style>
<![endif]-->

<table border=1 width=100% class="bbsBody">
<tr><td>
abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg
abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
<img src="http://www.blueidea.com/upload/1198990-2000sp3+ie5.gif">
</table>

39. js精确计算
<script>
document.write((6*2.3)+"<br>")
document.write(parseFloat((6*2.3).toFixed(12)))
</script>

40. xbm图片
<script>
pic = "#define count_width 16"+"\n"+
"#define count_height 1"+"\n"+
"static char count_bits[] = {0xaa,0xaa}"
</script>

<img width=96 src=javaScript:pic>

41. 动态设置一个对象的伪类
<style>
a {color:blue}
a:hover{color:red}
</style>

<script defer>
function setHover(obj)
{
var uqid=obj.id=obj.uniqueID
document.styleSheets[0].addRule("A:hover#"+uqid, "color:#"+(Math.random()*0xFFFFFF|0).toString(16))
}
for (var i=0; i<document.links.length; i++) setHover(document.links[i])
</script>

<a href="###" href_cetemp="###">link</a>
<a href="###">link</a>
<a href="###">link</a>
<a href="###">link</a>
<hr />

在css 2中可以用A:hover[uniqueID=value]代替

42. 同步服务器时间
<b>经典服务器时间: </b><span id=serverTime>正在同步...</span>
<script>
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
xmlhttp.open("GET", "http://www.blueidea.com/bbs/faq.html", false)
xmlhttp.setRequestHeader("Range", "bytes=-1")
xmlhttp.send()
var ts = new Date()-new Date(xmlhttp.getResponseHeader("Date"))
setInterval("serverTime.innerText=new Date(new Date().getTime()+ts).toLocaleString()", 1)
</script>

45.显示输入框
<html>
<head>
<script language="javascript">
function changeBox(status)
{
textbox.style.display = status ? "" : "none"
}
</script>

<script language="javascript" for="test" event="onpropertychange">
var propName = event.propertyName
var propValue = this[propName]

switch(propName)
{
case "checked":
changeBox(propValue)
break;
}
</script>
</head>

<body>
<input type="radio" id="test" name="radio" checked="true" />
<input type="radio" name="radio" />
<input id="textbox" />
</body>
</html> 

posted on 2007-01-19 12:55  hfyb  阅读(309)  评论(0编辑  收藏  举报

导航