<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: red;
}
</style>
<script>
window.onload = function(){
/**
* 點擊按鈕以后 修改box1 的大小
*/
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function(){
// 修改 box1 的寬度
/**
* 通過 js 修改元素的樣式
* 語法: 元素.style.樣式名 = 樣式值
*/
box1.style.width = '300px';
box1.style.height = '300px';
box1.style.backgroundColor = 'yellow';
}
// 讀取 元素的樣式
var btn02 = document.getElementById("btn02");
btn02.onclick = function(){
// 讀取 box1 的樣式
/**
* 語法: 元素.style.樣式名
* 通過 style 屬性設置 和讀取的 都是 內連樣式
* 無法讀取樣式表中的樣式
*/
// alert(box1.style.width)
/**
* 獲取元素的當前顯示的樣式 只能讀 不能修改
* 語法: 元素.currentStyle.樣式名 --> 只支持ie
* 可以讀當前元素顯示的樣式
* window.getComputedStyle(元素 null)[樣式名] -> 其它瀏覽器 使用這個 ->不支持 ie8 以下的瀏覽器
* window.getComputedStyle(元素 null).樣式名
* 如果獲取的樣式 沒有設置 則會獲取到真實的值 而不是默認值
*/
console.log(getStyle(box1,'width'));
}
/**
* 定義一個函數 用來獲取指定元素的當前的樣式
* 參數
* obj 要獲取樣式的元素
* name 要獲取的樣式名
*/
function getStyle(obj,name){
if(window.getComputedStyle){
// 正常瀏覽器的方式
return getComputedStyle(obj,null)[name];
}else{
// ie8 的方式
return obj.currentStyle[name];
}
}
}
</script>
</head>
<body>
<button id="btn01">點我一下</button>
<button id="btn02">點我一下2</button>
<br /> <br />
<div id="box1"> </div>
</body>
</html>