/*
1. 变量
2. 事件
3. 函数
4. 属性
*/
目前,关于事件我们只学了一个点击事件。
如果觉得前边获取元素时写的document.getElement(s)..太长了,那么可以通过声明变量来简化它
例如:
<script>
var box = document.getElementById(‘ box ‘)
var btn = document.getElementById(‘ btn ‘)
btn.onclick = function(){
box.style.background=" red "
}
</script>
可以看到利用js可以通过点击其他位置控制另一个元素样式的变化
利用这一点,我们做了一个小东西,以下是代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="../css/index.css" /> </head> <body> <div id="main"> <div id="word"> <span>请为下边的DIV设置样式:</span> <button id="set">点击设置</button> </div> <div id="box"></div> </div> <div id="bg"> <div id="center"> <div id="color"> <span>请选择背景色:</span> <button id="red">红</button> <button id="yel">黄</button> <button id="blue">蓝</button> </div> <div id="width"> <span>请选择宽度:</span> <button id="w200">200</button> <button id="w300">300</button> <button id="w400">400</button> </div> <div id="height"> <span>请选择高度:</span> <button id="h200">200</button> <button id="h300">300</button> <button id="h400">400</button> </div> <div id="choose"> <button id="reg">恢复</button> <button id="sure">确定</button> </div> </div> </div> <script> var set = document.getElementById (‘set‘); var box = document.getElementById (‘box‘); var bg = document.getElementById (‘bg‘); var red = document.getElementById (‘red‘); var yel = document.getElementById (‘yel‘); var blue = document.getElementById (‘blue‘); var w200 = document.getElementById (‘w200‘); var w300 = document.getElementById (‘w300‘); var w400 = document.getElementById (‘w400‘); var h200 = document.getElementById (‘h200‘); var h300 = document.getElementById (‘h300‘); var h400 = document.getElementById (‘h400‘); var reg = document.getElementById (‘reg‘); var sure = document.getElementById (‘sure‘); set.onclick = function(){ bg.style.display = ‘block‘; } red.onclick = function(){ box.style.background = ‘#f50b42‘; } yel.onclick = function(){ box.style.background = ‘#f9e74f‘; } blue.onclick = function(){ box.style.background = ‘#84a8f1‘; } w200.onclick = function(){ box.style.width = ‘200px‘; } w300.onclick = function(){ box.style.width = ‘300px‘; } w400.onclick = function(){ box.style.width = ‘400px‘; } h200.onclick = function(){ box.style.height = ‘200px‘; } h300.onclick = function(){ box.style.height = ‘300px‘; } h400.onclick = function(){ box.style.height = ‘400px‘; } reg.onclick = function(){ box.style.width = ‘142px‘; box.style.height = ‘142px‘; box.style.background = ‘#fff‘; } sure.onclick = function(){ bg.style.display = ‘none‘; } </script> </body> </html>
从这里,我初次感受到了 js 的灵活,好多东西还没见识到,要继续努力才是。