《JavaScript学习笔记二》:网页换肤
在我们的一些网页上提供了网页换肤这一功能,网页换肤就是指:网页的颜色有几种不同的选择供我们选择。例如,如下截图所示:
下面我们就来模拟实现这一功能:
由于功能比较简单,这里就直接贴代码:
<!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=gb2312" />
<title>无标题文档</title>
</head>
<style>
#div1 {width:200px;height:100px;background:red;border:1px solid:#999;display:block;}
</style>
<script>
function toRed()
{
var oDiv=document.getElementById('div1');
oDiv.style.background="red";
}
function toYellow()
{
var oDiv=document.getElementById('div1');
oDiv.style.background="yellow";
}
function toBlack()
{
var oDiv=document.getElementById('div1');
oDiv.style.background="black";
}
</script>
<body>
<input type="button" value="红色" onclick="toRed()" />
<input type="button" value="黄色" onclick="toYellow()" />
<input type="button" value="黑色" onclick="toBlack()" />
<div id="div1">
</div>
</body>
</html>
程序运行结果如下:
上面使用了三个函数,对应着三种颜色的选择,从代码中可以看出,三个函数的代码基本一样,因此,我们也可以选择用一个带参数的函数来实现。
<!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=gb2312" />
<title>无标题文档</title>
</head>
<style>
#div1 {width:100px;height:200px;border:1px solid:#999;background:red;display:block}
</style>
<script>
function setColor(content)
{
var oDiv=document.getElementById('div1');
oDiv.style.background=content;
}
</script>
<body>
<input type="button" value="红色" onclick="setColor('red')" />
<input type="button" value="黄色" onclick="setColor('yellow')" />
<input type="button" value="黑色" onclick="setColor('black')" />
<div id="div1">
</div>
</body>
</html>
参考资料
1、blue老师的js视频教程