学习js使用className遇到的疑惑
我在学习js时,想利用通过getElementById()获取得的ID来指明属性className等于一个css样式,我是想实现这样一个效果,当单击添加css样式按钮时,这个样式添加,当单击移出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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style type="text/css">
.b_img{
background-image: url(bwa.jpg);
background-repeat: no-repeat;
}
#db{
display: none;
}
</style>
</head>
<body id="con">
<input id="ab" value="添加背景" type="button" onclick="addBackround_img()"/>
<input id="db" value="移除背景" type="button" onclick="delectBackround_img()">
<script type="text/javascript">
function addBackround_img(){
//背景消失
var b_img=document.getElementById("con");
b_img.className="b_img";
//b_img.style.backgroundImage="url(bwa.jpg)";
//b_img.style.backgroundRepeat="no-repeat";
//移出背景的按钮出现
var db_button=document.getElementById("db");
db_button.style.display="block";
//显现背景的按钮消失
var ab_button=document.getElementById("ab");
ab_button.style.display="none";
}
function delectBackround_img(){
var d_img=document.getElementById("con");
d_img.style.backgroundImage="url()";
var ab_button=document.getElementById("ab");
ab_button.style.display="block";
var db_button=document.getElementById("db");
db_button.style.display="none";
}
</script>
</body>
</html>