摘要:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>JavaScript控制DIV樣式</title><style type='text/css'>p+div{width:100p
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript控制DIV樣式</title>
<style type='text/css'>
p+div{
width:100px;
height:100px;
background:#f00;
}
/* 按鈕樣式 */
button{
border:none;
height:30px;
width:60px;
}
/* 按鈕懸停樣式 */
button:hover{
background:#ff6700;
color:#fff;
cursor:pointer;
}
</style>
<script type='text/javascript'>
// 隨機(jī)數(shù)函數(shù)
function Rand(min,max){
return Math.floor(Math.random() * (max - min + 1));
}
window.onload = function(){
var height = 100;
var width = 100;
var max_height = 600;
var max_width = 600;
//設(shè)置一個(gè)顏色數(shù)組
var bgcolor = ['#f0f','#ff0','#000','#00f','#ff6700','#ccc','#00BFFF','#2F4F4F'];
// 獲取div元素
var div = document.getElementsByTagName('div')[0];
//變高
document.getElementsByTagName('button')[0].onclick = function(){
if(div.style.display == 'none'){
alert('請(qǐng)先顯示后在操作');
}else{
// div的元素的高度是否小于最大高度限制 小于就增加高度 否則提示
div.clientHeight < max_height ? (div.style.height = div.clientHeight + height + 'px') : alert('高度不能超過(guò)'+ max_height +'px');
}
}
//變寬
document.getElementsByTagName('button')[1].onclick = function(){
if(div.style.display == 'none'){
alert('請(qǐng)先顯示后在操作');
}else{
// div的元素的寬度是否小于最大寬度限制 小于就增加寬度 否則提示
div.clientWidth < max_width ? (div.style.width = div.clientWidth + width + 'px') : alert('寬度不能超過(guò)'+ max_width +
'px');
}
}
//變色
document.getElementsByTagName('button')[2].onclick = function(){
if(div.style.display == 'none'){
alert('請(qǐng)先顯示后在操作');
}else{
// 從bgcolor顏色數(shù)組中 隨機(jī)取出顏色 并賦值給div的背景
div.style.backgroundColor = bgcolor[Rand(0,bgcolor.length)];
}
}
//隱藏
document.getElementsByTagName('button')[3].onclick = function(){
if(div.style.display == 'none'){
alert('已經(jīng)隱藏了');
}else{
//隱藏div
div.style.display = 'none';
}
}
//顯示
document.getElementsByTagName('button')[4].onclick = function(){
if(div.style.display != 'none'){
alert('已經(jīng)顯示了');
}else{
//顯示div
div.style.display = 'block';
}
}
//重置
document.getElementsByTagName('button')[5].onclick = function(){
// 還原成最初的div
div.style.cssText = 'background:#f00;width:100px;height:100px;display:block;';
}
};
</script>
</head>
<body>
<p>
<button>變高</button>
<button>變寬</button>
<button>變色</button>
<button>隱藏</button>
<button>顯示</button>
<button>重置</button>
</p>
<div></div>
</body>
</html>
批改老師:韋小寶批改時(shí)間:2019-02-11 17:08:57
老師總結(jié):寫(xiě)的很不錯(cuò) JavaScript控制div的樣式在開(kāi)發(fā)中是最常見(jiàn)的 想要頁(yè)面有活力都會(huì)使用到!