摘要
1.函數傳參。
2.兩種操作屬性的方法。
3.style和className
一碰逸、函數傳參
改變背景顏色
函數傳參:參數就是占位符
- 什么時候用參數--函數里定不下來的東西
<strong>例子(1)改變div的顏色</strong>
<script>
function setColor(color) {
var oDiv = document.getElementById('div1');
oDiv.style.background = color;
}
</script>
<body>
<input type="button" value="變紅" onclick="setColor('red')">
<input type="button" value="變黃" onclick="setColor('yellow')">
<input type="button" value="變綠" onclick="setColor('green')">
<div id="div1"></div>
</body>
<strong>例子(2)改變Div的任意樣式</strong>
<script>
function setStyle(name, value) {
var oDiv = document.getElementById('div1');
oDiv.style[name] = value;
}
</script>
<body>
<input type="button" value="變寬" onclick="setStyle('width','400px')">
<input type="button" value="變高" onclick="setStyle('height','400px')">
<input type="button" value="變綠" onclick="setStyle('background','green')">
<div id="div1"></div>
</body>
二鸟废、兩種操作屬性的方法
- 什么時候用:要修改的屬性不固定
- 字符串和變量--區(qū)別和關系
<script>
function setText(name) {
var oTx = document.getElementById('txt1');
// 第一種操作屬性的方法
// oTx.value = 'hhhhh';
// 第二種操作屬性的方法
//oTx['value'] = 'ahkahdc';
oTx[name] = 'heheheheh'
// 第二種方法的優(yōu)勢在于屬性名稱是可以更改的 在JS中但凡是可以用點的都可以改成用[],但是反過來不成立
}
</script>
<body>
<input id="txt1" type="text">
<input type="button" value="改變文字" onclick="setText('title')">
</body>
3雁乡、style和className
- 元素.style屬性=xxx是修改行間樣式
- 之后再修改className不會有效果
通過下邊的代碼運行,在瀏覽器中審查元素會發(fā)現:
style加樣式 在行間
style取樣式 在行間
<script>
// style加樣式 行間
// style取樣式 行間
function toRed() {
var oDiv = document.getElementById('div1');
//oDiv.style.background = 'red';
}
</script>
<body>
<input type="button" value="變紅" onclick="toRed()">
<div id="div1"></div>
</body>
示例1
示例2
如果換成class又會出現另外的情形
我么先看一下在CSS中的樣式優(yōu)先級
-
*
<標簽<class<ID<行間
再給一個例子作為比較
<style>
#div1{ width:200px; height: 200px; border: solid 1px}
.box{background: green}
</style>
<script>
function toRed() {
var oDiv = document.getElementById('div1');
oDiv.className = 'box';
}
function toGreen() {
var oDiv = document.getElementById('div1');
oDiv.style.background = 'green';
}
</script>
<body>
<input type="button" value="變紅" onclick="toRed()">
<input type="button" value="變綠" onclick="toGreen()">
<div id="div1"></div>
</body>
示例3
示例4
當先點擊紅色在點擊綠色,div顏色正常顯示糜俗,但是如果反過來就會發(fā)現先點擊綠色后在點擊變紅則無法改變顏色踱稍,這就是因為行間樣式的優(yōu)先級大于class的原因,在審查元素的代碼變化中也能看到悠抹。
<strong>因此在這里需要特別注意珠月,對同一個元素,要么從頭到尾一只操作class楔敌,要么一直操作style啤挎,而不要混著來,這樣會避免一些很難查找到的問題</strong>