1、內聯樣式
1.1、直接寫入元素的標簽內部
<html>
<title>js樣式內聯寫法</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<!--js內聯寫法01開始-->
<!--當鼠標點擊圖片時跳出彈窗顯示1223-->
<div class="img">
單擊事件:
<img src="images/001.jpg" οnclick="alert(1223)"></img>
</div>
<!--js內聯寫法01結束-->
</body>
</html>
1.2、是寫入到標簽中
給元素添加id
通過getElementById('XX');方法定位到該元素,給該元素添加觸發事件
注意:<script></script>標簽應該放在</body>之后
<html>
<title>js樣式內聯寫法</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<!--js內聯寫法02開始-->
<div class="img">
單擊事件:
<img src="images/002.jpg" id='yuansu'></img>
</div>
<!--js內聯寫法02結束-->
</body>
<script>
//js代碼
//找到XX元素,一般給元素加id
yuansuojb=document.getElementById('yuansu');
//給xx元素加事件
yuansuojb.οnclick=function(){
//代碼段
alert(1);
}
//觸發事件
</script>
</html>
2、外聯樣式
將js的代碼寫到.js的文件中,並在HTML中引用
.html文件內容如下:
<html>
<title>js樣式外聯寫法</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<div class="img">
外聯寫法--單擊事件:
<img src="images/003.jpg" id='yuansu'></img>
</div>
</body>
<script src='js/index.js'></script>
</html>
.js文件內容如下:
//js代碼
//找到XX元素,一般給元素加id
yuansuojb=document.getElementById('yuansu');
//給xx元素加事件
yuansuojb.οnclick=function(){
//代碼段
var str="hello world !!!";
alert(str);
}