日常的js代码中,有很多的重复js代码,例如下面这个,我们点击不同的颜色按钮,可以将div中的颜色进行变换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>变换颜色之函数传值</title>
<style>
#div1 {
width: 200px;
height: 100px;
background: red;
border: 1px solid #999;
}
</style>
</head>
<body>
<div id="div1"></div>
<input type="button" value="变绿色" onclick="toGreen()">
<input type="button" value="变黄色" onclick="toYellow()">
<input type="button" value="变黑色" onclick="toBlack()">
<script type="text/javascript">
function toGreen(){
var div1 = document.getElementById('div1') ;
div1.style.background = 'green';
}
function toYellow(){
var div1 = document.getElementById('div1') ;
div1.style.background = 'yellow';
}
function toBlack(){
var div1 = document.getElementById('div1') ;
div1.style.background = 'black';
}
</script>
</body>
</html>
'''
可以发现上面的代码中js代码基本全部是重复的,可以将js代码进行改造,改造后代码如下
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>变换颜色之函数传值</title>
<style>
#div1 {
width: 200px;
height: 100px;
background: red;
border: 1px solid #999;
}
</style>
</head>
<body>
<div id="div1"></div>
<input type="button" value="变绿色" onclick="setColor('green')">
<input type="button" value="变黄色" onclick="setColor('yellow')">
<input type="button" value="变黑色" onclick="setColor('black')">
<script type="text/javascript">
function setColor(color){
var div1 = document.getElementById('div1') ;
div1.style.background = color;
}
</script>
</body>
</html>
补充说明一下
js中操作属性的方法有2种,一种是通过.的方式去取值操作,还有一种则是通过[‘属性名’]的方式取值
例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>变换颜色之函数传值</title>
<style>
#div1 {
width: 200px;
height: 100px;
background: red;
border: 1px solid #999;
}
</style>
</head>
<body>
<div id="div1"></div>
<input type="button" value="变宽" onclick="setStyle('width','300px')">
<input type="button" value="变高" onclick="setStyle('height','200px')">
<input type="button" value="变绿" onclick="setStyle('background','green')">
<script type="text/javascript">
function setStyle(name,value){
var div1 = document.getElementById('div1') ;
div1.style[name] = value;
}
</script>
</body>
</html>
'''
网友评论