练习地址:http://www.fgm.cc/learn/lesson2/05.html
用户输入属性和属性值,确定修改,重置reset。
实现思路:
写一个3参数函数:元素、属性、属性值。确认按钮点击事件就是通过这个函数修改div。重置按钮使用removerAttribute()方法去掉属性。
HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>函数传参,改变Div任意属性的值</title>
<link rel="stylesheet" type="text/css" href="5_changAttr.css">
</head>
<body>
<div id="container">
<span>属性名:</span>
<input type="text" value="background">
<span>属性值:</span>
<input type="text" value="blue">
<button id="conf">确定</button>
<button id="reset">重置</button>
<div class="show">在上方输入框输入“属性名”及“属性值”,点击确定按钮查看效果。</div>
</div>
<script src="5_changAttr.js"></script>
</body>
</html>
CSS
#container {
width: 240px;
margin: 0 auto;
text-align: center;
font-size: 14px;
line-height: 30px;
}
input {
outline: none;
border: 1px solid lightgray;
padding-left: 5px;
}
.show {
width: 192px;
height: 200px;
background: black;
color: white;
position: relative;
left: 25px;
top: 10px;
padding: 10px;
font-size: 12px;
line-height: 16px;
text-align: left;
}
JavaScript
window.onload = function() {
var conf = document.getElementById("conf");
var reset = document.getElementById("reset");
var show = document.getElementsByClassName("show")[0];
function change(elem,attr,valu) {
elem.style[attr] = valu;
}
conf.onclick = function() {
var attri = document.getElementsByTagName("input")[0].value;
var attrValue = document.getElementsByTagName("input")[1].value;
change(show,attri,attrValue);
}
reset.onclick = function() {
show.removeAttribute("style");
}
}
我好菜的,老打错字。remember:
getElementById();
getElementsByTagName()[0];
getElementsByClassName()[0];