首页 > 代码库 > js改变元素的class来实现改变元素的CSS样式

js改变元素的class来实现改变元素的CSS样式

<!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 type="text/css">
div{ width:100px; height:100px; background-color:#F00;}/*如果这里用的事id的话,则一直都是这个样式,因为id的优先级比class高*/
.box{ width:200px; height:200px; background-color:#9F0;}
</style>
</head>

<body>
<div id="div1"></div>
</body>

</html>
<script type="text/javascript">
    if(document.getElementsByTagName){
        var div = document.getElementsByTagName("div")[0];
        
        div.onmouseover=function(){
            div.className="box";
        }
        div.onmouseout=function(){
            div.className="";
        }
    }
</script>