1. html部分
<div>
<div id="tab">
<h2>标题一</h2>
<h2>标题二</h2>
<h2>标题三</h2>
<h2>标题四</h2>
</div>
<dl id="tabcon">
<dd>内容一</dd>
<dd>内容二</dd>
<dd>内容三</dd>
<dd>内容四</dd>
</dl>
</div>
<div id="tab">
<h2>标题一</h2>
<h2>标题二</h2>
<h2>标题三</h2>
<h2>标题四</h2>
</div>
<dl id="tabcon">
<dd>内容一</dd>
<dd>内容二</dd>
<dd>内容三</dd>
<dd>内容四</dd>
</dl>
</div>
2. js部分
<script type="text/javascript" defer="defer">
var tab = document.getElementById("tab").getElementsByTagName("h2");
function swap(n) {
returnfunction() {
for(var i=0; i<tab.length; i++) {
document.getElementById("tabcon"+ i).style.display ="none";
document.getElementById("tab"+ i).className ="";
}
document.getElementById("tabcon"+ n).style.display ="block";
document.getElementById("tab"+ n).className ="focus";
}
}
for(var i=0; i<tab.length; i++) {
tab[i].setAttribute("id", "tab"+ i);
if(window.addEventListener) {
tab[i].addEventListener("mouseover", swap(i), false);
} elseif(window.attachEvent) {
tab[i].attachEvent("onmouseover", swap(i));
}
}
var tabcon = document.getElementById("tabcon").getElementsByTagName("dd");
for(i=0; i<tabcon.length; i++) {
tabcon[i].setAttribute("id", "tabcon"+ i);
}
if(document.createEvent) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'mouseover', true, false);
tab[0].dispatchEvent(evObj);
} elseif( document.createEventObject) {
tab[0].fireEvent('onmouseover');
}
</script>
var tab = document.getElementById("tab").getElementsByTagName("h2");
function swap(n) {
returnfunction() {
for(var i=0; i<tab.length; i++) {
document.getElementById("tabcon"+ i).style.display ="none";
document.getElementById("tab"+ i).className ="";
}
document.getElementById("tabcon"+ n).style.display ="block";
document.getElementById("tab"+ n).className ="focus";
}
}
for(var i=0; i<tab.length; i++) {
tab[i].setAttribute("id", "tab"+ i);
if(window.addEventListener) {
tab[i].addEventListener("mouseover", swap(i), false);
} elseif(window.attachEvent) {
tab[i].attachEvent("onmouseover", swap(i));
}
}
var tabcon = document.getElementById("tabcon").getElementsByTagName("dd");
for(i=0; i<tabcon.length; i++) {
tabcon[i].setAttribute("id", "tabcon"+ i);
}
if(document.createEvent) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'mouseover', true, false);
tab[0].dispatchEvent(evObj);
} elseif( document.createEventObject) {
tab[0].fireEvent('onmouseover');
}
</script>
html代码与js分离,不干扰搜索引擎抓取
兼容IE和Fx,其中没有on的事件是火狐下的写法