修改文本颜色
box里的文字从黑色变成了蓝色
移出移入改变背景颜色
嵌入式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>移入移出改变背景颜色</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: #ccc;
margin: 100px auto;
}
</style>
<script type="text/javascript">
//当页面加载完成时会自动激发onload事件
window.onload = function(){
//mouseover
document.getElementById('box').onmouseover = function(){
//DOM 元素.style.css属性名 = 属性值
//document.getElementById('box').style.background = 'pink';
//this.style.background-color = 'pink'; //错误,css属性名写法错误
//background-color:backgroundColor
this.style.backgroundColor = 'pink';
}
document.getElementById('box').onmouseout = function(){
this.style.backgroundColor = '#ccc';
}
}
</script>
</head>
<body>
<h1>onload事件</h1>
<div id="box"></div>
</body>
</html>
行内式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>移入移出改变背景颜色</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: #ccc;
margin: 100px auto;
}
</style>
</head>
<body>
<h1>js引入的方式三:行内式</h1>
<div id="box" onmouseover = 'this.style.backgroundColor="pink";'
onmouseout = 'this.style.backgroundColor="#ccc";'
></div>
</body>
</html>
外联式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>移入移出改变背景颜色</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: #ccc;
margin: 100px auto;
}
</style>
</head>
<body>
<h1>js引入的方式二:外链式</h1>
<div id="box"></div>
<script src="first.js"></script>
</body>
</html>
js代码
// 单行注释:只能写脚本代码 ctrl + /
/* 多行注释 ctrl + shift + /
鼠标移入移出改变背景颜色
mouseover/ mouseout
*/
//mouseover
document.getElementById('box').onmouseover = function(){
//DOM 元素.style.css属性名 = 属性值
//document.getElementById('box').style.background = 'pink';
//this.style.background-color = 'pink'; //错误,css属性名写法错误
//background-color:backgroundColor
this.style.backgroundColor = 'pink';
}
document.getElementById('box').onmouseout = function(){
this.style.backgroundColor = '#ccc';
}