看了这个站首页里的js代码,感觉有些脚本比较有用,于是自己整理了下,放在这里,也算是偶的一点小练习。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<style type="text/css">
#search{
border:1px solid #ccc;
color:#999;
}
</style>
<script type="text/javascript">
<!--
function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+, NS6 and Mozilla
// By Scott Andrew
{
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent("on"+evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
function externalLinks(){ //设定属性rel为external的连接在新页面打开
if(!document.getElementsByTagName) return ;
var anchors=document.getElementsByTagName("a");
for(var i=0;i<anchors.length;i++){
anchor=anchors[i];
if(anchor.getAttribute("href")&&anchor.getAttribute("rel")=="external"){
anchor.setAttribute("target","_blank");
}
}
}
function onSearchFocus(){ //搜索框获取焦点时
var search=document.getElementById("search");
if(search.value=="请输入关键字"){ //如果输入框内容是“请输入关键字”,则清空内容,并设顶文字颜色为黑色
search.value="";
search.style.color="#000"
}
}
function onSearchBlur(){ //搜索框失去焦点时
var search=document.getElementById("search");
if(search.value==""){ //如果输入框内容为空,则设定文字颜色为灰色,内容为“请输入关键子”
search.style.color="#999";
search.value="请输入关键字"
}
}
addEvent(window,"load",externalLinks)
-->
</script>
</head>
<body>
<p>
[External links]<br />
<a href="http://www.qq.com" rel="external">QQ.com</a><br />
<a href="http://www.163.com" rel="external">163.com</a><br />
</p>
<p>
[internal Links]<br />
<a href="http://www.blueidea.com" rel="internal">BlueIdea.com</a><br />
<a href="http://www.51js.com" rel="internal">51Js.com</a><br />
</p>
<p>
[Input Test]<br />
<input type="text" id="search" value="请输入关键字" size="20" onFocus="onSearchFocus()" onblur="onSearchBlur()" />
</p>
</body>
</html>
注:externalLinks()函数里认识了getAttribute()和setAttribute()的用法。
addEvent()函数是一个添加事件的函数,在ie和ns下兼容。