日期:2014-05-16  浏览次数:20315 次

关于添加class的问题

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
.div{
width:100px;
height:30px;
background:#DCDCDC;
}
.active{
border:1px solid #00BCF3;
}
</style>
<script>
window.onload=function(){
var hover=document.getElementById('btn')
hover.onmouseover=function(){
hover.className='active';
}
}
</script>
</head>

<body>
<div id="btn" class="div"></div>
</body>
</html>


请问下 我这个效果是想 在class=“div”后面添加active这个样式 而不是把div样式替换了 应该怎么做
还有鼠标移开的时候 active这个样式应该怎么移除
------解决方案--------------------
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
.div{
    width:100px;
    height:30px;
    background:#DCDCDC;
    }
.active{
    border:1px solid #00BCF3;
    }
</style>
<script>
window.onload=function(){
    var hover=document.getElementById('btn')
    hover.onmouseover=function(){
if(hover.className.indexOf('active')==-1){
         hover.className+=' active';
}
    }
hover.onmouseout=function(){
if(hover.className.indexOf('active')!=-1){
         var b=hover.className.split(" ");
for(var i=0;i<b.length;i++){
if(b[i]=='active'){
delete b[i];
}
}
hover.className=b.join(' ');
}
    }
}
</script>
</head>
 
<body>
<div id="btn" class="div">123</div>
</body>
</html>