JavaScript学习第一天(对html元素相关操作)

1.JavaScript:写入 HTML 输出

可以直接将html代码写入JS中

<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script>

2.JavaScript:对事件作出反应

alert() 函数在 JavaScript 中并不常用,但它对于代码测试非常方便。

<button type="button" onclick="alert('Welcome!')">点击这里</button>

3.JavaScript:改变 HTML 内容

<!DOCTYPE html>
<html>
<body>

<h1>我的第一段 JavaScript</h1>

<p id="demo">
JavaScript 能改变 HTML 元素的内容。
</p>

<script>
function myFunction()
{
x=document.getElementById("demo");  // 找到元素
x.innerHTML="Hello JavaScript!";    // 改变内容
}
</script>

<button type="button" onclick="myFunction()">点击这里</button>

</body>
</html>

4.JavaScript:改变 HTML 图像

<!DOCTYPE html>
<html>
<body>
<script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("bulbon"))
  {
  element.src="/i/eg_bulboff.gif";
  }
else
  {
  element.src="/i/eg_bulbon.gif";
  }
}
</script>

<img id="myimage" onclick="changeImage()" src="/i/eg_bulboff.gif">

<p>点击灯泡来点亮或熄灭这盏灯</p>

</body>
</html>

5.JavaScript:改变 HTML 样式

<!DOCTYPE html>
<html>
<body>

<h1>我的第一段 JavaScript</h1>

<p id="demo">
JavaScript 能改变 HTML 元素的样式。
</p>

<script>
function myFunction()
{
x=document.getElementById("demo") // 找到元素
x.style.color="#ff0000";          // 改变样式
}
</script>

<button type="button" onclick="myFunction()">点击这里</button>

</body>
</html>

6.JavaScript:验证输入

<!DOCTYPE html>
<html>
<body>

<h1>我的第一段 JavaScript</h1>

<p>请输入数字。如果输入值不是数字,浏览器会弹出提示框。</p>

<input id="demo" type="text">

<script>
function myFunction()
{
var x=document.getElementById("demo").value;
if(x==""||isNaN(x))
    {
    alert("Not Numeric");
    }
}
</script>

<button type="button" onclick="myFunction()">点击这里</button>

</body>
</html>

 

posted @ 2016-06-13 11:14  沅代码_cd  阅读(149)  评论(0编辑  收藏  举报