JavaScript控制DIV样式

Original 2019-02-11 16:54:02 287
abstract:<!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'>

// 随机数函数

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;

//设置一个颜色数组

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('请先显示后在操作');

}else{

// div的元素的高度是否小于最大高度限制 小于就增加高度 否则提示

div.clientHeight < max_height ? (div.style.height = div.clientHeight + height + 'px') : alert('高度不能超过'+ max_height +'px');

}

}

//变宽

document.getElementsByTagName('button')[1].onclick = function(){

if(div.style.display == 'none'){

alert('请先显示后在操作');

}else{

// div的元素的宽度是否小于最大宽度限制 小于就增加宽度 否则提示

div.clientWidth < max_width ? (div.style.width = div.clientWidth  + width + 'px') : alert('宽度不能超过'+ max_width +

'px');

}

}

//变色

document.getElementsByTagName('button')[2].onclick = function(){

if(div.style.display == 'none'){

alert('请先显示后在操作');

}else{

// 从bgcolor颜色数组中 随机取出颜色 并赋值给div的背景

div.style.backgroundColor = bgcolor[Rand(0,bgcolor.length)];

}

}

//隐藏

document.getElementsByTagName('button')[3].onclick = function(){

if(div.style.display == 'none'){

alert('已经隐藏了');

}else{

//隐藏div

div.style.display = 'none';

}

}

//显示

document.getElementsByTagName('button')[4].onclick = function(){

if(div.style.display != 'none'){

alert('已经显示了');

}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>&nbsp;

<button>变宽</button>&nbsp;

<button>变色</button>&nbsp;

<button>隐藏</button>&nbsp;

<button>显示</button>&nbsp;

<button>重置</button>

</p>

<div></div>

</body>

</html>


Correcting teacher:韦小宝Correction time:2019-02-11 17:08:57
Teacher's summary:写的很不错 JavaScript控制div的样式在开发中是最常见的 想要页面有活力都会使用到!

Release Notes

Popular Entries