1.在js中修改css样式
事件可以在三种情况下发生,分别是:
(1)在页面加载的时候
(2)在input区内容改变的时候
(3)点击
下面的栗子是(1)和(3)的结合,注意表达式中添加了style,另外需要注意的是在css中属性名称采用的格式是-(横杆),但是在js中使用的是骆驼式命名法。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<p id="test">Hello World!</p>
<button id="btn">Click Me</button>
<script src="script.js"></script>
</body>
</html>
script.js
/*
* @Author: Lin
* @Date: 2017-07-23 17:34:47
* @Last Modified by: Lin
* @Last Modified time: 2017-07-23 17:41:06
*/
document.getElementById("test").style.color = "blue";
var x = document.getElementById("btn");
x.onmouseover = function() {
document.getElementById("test").style.backgroundColor = "yellow";
};
x.onmouseout = function() {
document.getElementById("test").style.backgroundColor = "white";
} // 需要特别注意此处是backgroundColor不是backgound-color
2.用js和html、css结合实现动画
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button id="btn">Click Me</button>
<div id="container">
<div id="animate"></div>
</div>
<!-- 将script放在前面的话会报错:move函数是null -->
<script src="script.js"></script>
</body>
</html>
style.css
/*
* @Author: Lin
* @Date: 2017-07-23 19:17:36
* @Last Modified by: Lin
* @Last Modified time: 2017-07-23 19:41:07
*/
#container {
width: 400px;
height: 400px;
position: relative;
background-color: #00EE00;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
script.js
/*
* @Author: Lin
* @Date: 2017-07-23 19:15:07
* @Last Modified by: Lin
* @Last Modified time: 2017-07-23 19:38:00
*/
// 发现一个奇特的现象,move后面如果加上括号的话,没有点击按钮就直接执行动画;
// 将move后面的括号去掉,就可以达到预期的效果
document.getElementById("btn").onclick = move;
function move() {
var ani = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5); // 每5ms执行一次frame函数
function frame() {
if (pos == 350) {
clearInterval(id); // 前面添加变量id而不是直接用setInterval的原因
} else {
pos++;
ani.style.top = pos + 'px';
ani.style.left = pos + 'px';
}
}
}
/*
document.getElementById("btn").onclick = move();
和
document.getElementById("btn").onclick = move;
两者的执行结果不同
*/
注:setInterval(code,milliseconds)
表示每milliseconds时间就执行code部分的内容,在上面的例子中,单独声明了变量id,是为了后面的clearInterval,如果不需要clearInterval,则可以不用单独声明变量,直接使用setInterval.