各种实例
http://www.fgm.cc/learn/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>控制div属性</title>
<script src="https://code.jquery.com/jquery-3.2.1.js" type="text/javascript"></script>
<style>
#outer{margin: 0 auto; padding: 0; text-align: center;}
#div1{border: 1px solid ;width: 100px;height: 100px;background-color:black; margin: 40px auto;display: block}
</style>
<script>
//更改样式函数
//传入三个值,要操作的对象,要操作的属性,属性的值
var changes=function(elem,attr,value){
elem.style[attr]=value//style[]也可换做style.attr
};
window.οnlοad=function(){
var oBtn=document.getElementsByTagName("input");
//获取要操作的div
var oDiv=document.getElementById("div1");
//要更改的属性数组
var oAttr=["width","height","background","display","display"];
//对应的属性的值
var oValue=["300px","300px","red","none","block"];
//
for (var i=0;i<oBtn.length;i++){
//设置每个按钮的下标索引值
//之所以不直接用oBtn[i],是因为当我们点击每个oBtn在点击的时候,是在for循环结束后才执行。
//用oBtn[i]获取到的是循环结束的最后一项,于是用自定义属性或者闭包都可以解决。
//因为点击事件是不知道什么时候进行的,而循环是快速进行的,所以当点击的时候,循环已经循环完了。
oBtn[i].index=i;
oBtn[i].οnclick=function(){
//当this.index的值等于最后一个索引(即重置按钮的索引),后面的那句话执行
//将之前设置的样式用""空字符串覆盖,即移去之前添加的行内样式
this.index == oBtn.length - 1 && (div1.style.cssText = "");
changes(div1,oAttr[this.index],oValue[this.index])
}
}
};
// $(function () {
// $(".btn1").click(function () {
// $("#div1").css('width','200px')
// })
// $('.btn2').click(function () {
// $("#div1").css('height','200px')
// })
// $('.btn3').click(function () {
// $('#div1').css('backgroundColor','blue')
// })
// $('.btn4').click(function () {
// $('#div1').css('display','none')
// })
// $('.btn5').click(function () {
// $('#div1').css({'width':'100','height':'100','backgroundColor':'black','display':'block'})
// })
// })
</script>
</head>
<body>
<div id="outer">
<input type="button" class="btn1" value="变宽">
<input type="button" class="btn2" value="变高">
<input type="button" class="btn3" value="变色">
<input type="button" class="btn4" value="隐藏">
<input type="button" class="btn5" value="重置">
<div id="div1" style="display: block"></div>
</div>
</body>
</html>