<!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>Document</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: #000;
}
</style>
<script>
window.onload = function () {
function Color(color) {
var box = document.getElementById("box");
box.style.backgroundColor = color;
}
}
</script>
</head><body>
<input type="button" value="红" onclick="Color('red')">
<input type="button" value="绿" onclick="Color('green')">
<input type="button" value="蓝" onclick="Color('blue')">
<div id="box"></div>
</body></html>求大神指点为什么去掉window.onload后js无法运行,会失效,急急
<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>Document</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: #000;
}
</style>
<script>
window.onload = function () {
function Color(color) {
var box = document.getElementById("box");
box.style.backgroundColor = color;
}
}
</script>
</head><body>
<input type="button" value="红" onclick="Color('red')">
<input type="button" value="绿" onclick="Color('green')">
<input type="button" value="蓝" onclick="Color('blue')">
<div id="box"></div>
</body></html>求大神指点为什么去掉window.onload后js无法运行,会失效,急急
要去掉window.onload,让Color函数处于全局作用域中才行。
因为Color函数处于window.onload的事件处理函数的局部作用域中的啊。
只能在这个事件处理函数中访问。在别的地方都访问不到。
window.Color=function(color) {
var box = document.getElementById("box");
box.style.backgroundColor = color;
}
}