批改状态:合格
老师批语:
同CSS样式表一样,js引入的方式也有三种,而且引入的三种方式也相同。
直接在元素的事件方法属性上面写js代码。
将js脚本写在<script>标签中,仅限当前页面使用。
将js脚本写到外部的js文件中,可以给任何引用该js文件的页面的使用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js的三种引入方式</title>
</head>
<body>
<!-- 第一种:直接把js代码在元素的事件方法属性上面 -->
<h2 id="tips" onclick="alert(this.id)">点击获取本元素的id值</h2>
<h2 id="tips" onclick="alert(id)">点击得到本元素的id值</h2>
<h2 id="tips" onclick="alert('你点了我吗?')">弹出一段话</h2>
<!-- 第二种:将js脚本写在script标签中,仅当前页面使用 -->
<form action="">
<input type="text" name="username" placeholder="用户名">
<button type="button" onclick="check(username)">验证</button>
</form>
<script>
function check (username) {
// 该函数用来验证用户名是否为空
if (username.value.length === 0) {
alert('用户名不能为空');
} else {
alert('验证通过');
}
}
</script>
<!-- 第三种:将js脚本写在外面单独的js文件中 -->
<style>
#ball {
width: 80px;
height: 80px;
background-color: lightgreen;
border-radius: 50%;
box-shadow: 2px 2px 2px #888;
/* 小球相于对原始位置发生位移 */
position: relative;
}
</style>
<div id="ball"></div>
<script src="js01.js"></script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
// 获取小球
var ball = document.getElementById('ball');
// 设置动画函数
function running(){
var count = 0; // 设置计数器并初始化
// 设置定时器方法,每隔100毫秒间歇调用
var timer = setInterval(function (){
// 当运行次数小于100时,自动递增左和上的坐标值
if (count < 100) {
ball.style.left = ball.style.top = count + 'px';
count++;
} else { // 否则就清除定时器终止运动
clearInterval(timer);
}
}, 100);
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号