JS学习笔记3

来源:互联网 发布:水果作曲软件中文版 编辑:程序博客网 时间:2024/05/22 12:30
【例1】
网页实现的功能是将一个初始为红色的正方框通过三个不同的案件的点击变成绿色、黄色、黑色。
比较暴力的代码:
<!DOCTYPE html><html><head><!--meta charset="utf-8"--><title>网页</title><style>#div1 {width:200px; height:200px; background:red;}</style><script>function toGreen() {var oDiv = document.getElementById('div1');oDiv.style.background='green';}function toYellow() {var oDiv = document.getElementById('div1');oDiv.style.background='yellow';}function toBlack() {var oDiv = document.getElementById('div1');oDiv.style.background='black';}</script></head><body><input type="button" value="变绿" onclick="toGreen()" /><input type="button" value="变黄" onclick="toYellow()" /><input type="button" value="变黑" onclick="toBlack()" /><div id="div1"></div></body></html>
函数传参:参数就是占位符
什么时候用传参--函数中有一个东西定不下来的时候
用函数传参简化的代码:
<!DOCTYPE html><html><head><!--meta charset="utf-8"--><title>网页</title><style>#div1 {width:200px; height:200px; background:red;}</style><script>function setColor(color) {var oDiv = document.getElementById('div1');oDiv.style.background = color;}</script></head><body><input type="button" value="变绿" onclick="setColor('green')" /><input type="button" value="变黄" onclick="setColor('yellow')" /><input type="button" value="变黑" onclick="setColor('black')" /><div id="div1"></div></body></html>
改变div的任意样式
【例2】
初始以红色方框,改变方框的宽度,高度,颜色,有点暴力的代码
<!DOCTYPE html><html><head><!--meta charset="utf-8"--><title>div改变样式</title><style>#div1 {width:200px; height:200px; background:red;}</style><script>function toWidth() {var oDiv = document.getElementById('div1');oDiv.style.width = '400px';}function toHeight() {var oDiv = document.getElementById('div1');oDiv.style.height = '400px';}function toGreen() {var oDiv = document.getElementById('div1');oDiv.style.background = 'green';}</script></head><body><input type="button" value="变宽" onclick="toWidth()" /><input type="button" value="变高" onclick="toHeight()" /><input type="button" value="变绿" onclick="toGreen()" /><div id="div1"></div></body></html>

可以适当修改,得到下面的代码

<!DOCTYPE html><html><head><!--meta charset="utf-8"--><title>div改变样式</title><style>#div1 {width:200px; height:200px; background:red;}</style><script>function setStyle(name , value) {    var oDiv = document.getElementById('div1');    oDiv.style[name] = value;}</script></head><body><input type="button" value="变宽" onclick="setStyle('width','400px')" /><input type="button" value="变高" onclick="setStyle('height','400px')" /><input type="button" value="变绿" onclick="setStyle('background','green')" /><div id="div1"></div></body></html>
【例3 改文字(扩展)】--两种操作属性的方法
<!DOCTYPE html><html><head><!--meta charset="utf-8"--><title>改文字</title><script>function setText() {var oTxt = document.getElementById('txt1');//第一种操作属性的方法//oTxt.value = 'abcdefg';//第二种操作属性的方法oTxt['value'] = 'abcdefg';}</script></head><body><input id="txt1" type="text" /><input type="button" value="改变文字" onclick="setText()" /></body></html>










0 0
原创粉丝点击