JavaScript 能做什么
-
JavaScript 能改变Html内容
<div> <p id="demo"></p> <button type="button" onclick="document.getElementById('demo').innerText='I am learning javascript'">点我!</button> </div> <script> let element = document.getElementById("demo"); element.innerText = "hello javascript"; </script>
-
JavaScript 能改变HTML属性的值
<div> <img id="dog" src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3599475514,2710235154&fm=26&gp=0.jpg"/> <button type="button" onclick="document.getElementById('dog').src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1607407045721&di=6113e0b45a16b31e0a283dc8bc36a43a&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fbaike%2Fpic%2Fitem%2F3b87e950352ac65c39576482fbf2b21192138af4.jpg'"> 点我 </button> </div>
-
JavaScript 能够改变CSS样式
<div> <p id="test">test</p> <button type="button" onclick="document.getElementById('test').style.color='red'"> 点我变成红色 </button> </div>
-
Javascript 能够隐藏 HTML 元素
<div> <p id="test">test</p> <button type="button" onclick="document.getElementById('test').style.display='none'"> 点我隐藏 </button> </div>
-
Javascript 能够显示隐藏的 HTML 元素
<div> <p id="test" style="display: none">test</p> <button type="button" onclick="document.getElementById('test').style.display='block'"> 点我显示 </button> </div>
在何处插入JavaScript
-
<head> 中的 JavaScript
<head> <meta charset="UTF-8"> <title>First</title> <script> function myFunction() { document.getElementById("demo").innerHTML = "段落已更改"; } </script> </head> <body> <div> <p id="demo">这是初始内容</p> <button type="button" onclick="myFunction()">点我更改内容</button> </div>
-
<body> 中的 JavaScript
<body> <script> function myFunction() { document.getElementById("demo").innerHTML = "段落已更改"; } </script> <div> <p id="demo">这是初始内容</p> <button type="button" onclick="myFunction()">点我更改内容</button> </div> </body>
-
外部文件中的Js
<p id="demo">一个段落。</p> <button type="button" onclick="myFunction()">试一试</button> <p>(myFunction 存储在名为 "myScript.js" 的外部文件中。)</p> <script src="/demo/myScript.js"></script>
-
外部URL中的JavaScript
<p id="demo">一个段落。</p> <button type="button" onclick="myFunction()">试一试</button> <p>(myFunction 存储在名为 "myScript.js" 的外部URL中。)</p> <script src="https://www.w3school.com.cn/demo/myScript.js"></script>
JavaScript输出
-
写入HTML输出
<script > document.write(5 + 6); </script>
-
写入HTML元素
<script> document.getElementById("demo").innerHTML = 5 + 6; </script>
-
写入窗口提示框
<script> window.alert(5 + 6); </script>
-
写入浏览器控制台
<script> console.log(5 + 6); </script>