JavaScript中兩種操作屬性的方法
-
點-.
用法:元素.屬性
-
方括号->[ ]
用法:元素[‘屬性’]
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 200px;
height: 200px;
background: red;
color: white;
}
</style>
</head>
<body>
<div id="box">這是文字</div>
<script>
var box = document.getElementById('box');
box.onclick = function () {
box.style.width = '300px';
}
//第二種方法
//box['onclick'] = function () {
// box['style']['width'] = '300px';
//}
</script>
</body>
</html>
特别注意:兩種屬性操作可以一起使用(意思是.和[ ]可以混用)
例子:
box.οnclick=function(){
box['style'].width = '300px';
}
遇到像
font-size
也可以用
box.onclick = function () {
box.style.fontSize='36px';
box.style['font-size'] = '36px';
}
常用的屬性:
- id
- className
- value
- style(background、color、width、height、cssText)
- innerHTML
- href
- src
- tagName
舉例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 200px;
height: 200px;
background: red;
color: white;
}
</style>
</head>
<body>
<div id="box" class="active">這是文字</div>
<input id='input1' type="text" value="請輸入密碼:">
<p id="txt">
這是文字内容
<span>這是副标題</span>
</p>
<script>
var box = document.getElementById('box');
var input1 = document.getElementById('input1');
var txt = document.getElementById('txt');
box.onclick = function () {
// box.style.width = '300px';
// box.style.height = '300px';
// box.style.background = 'green';
box.style.cssText = 'width:300px;height:300px;background:green';
}
//console.log(txt.innerHTML);
txt.innerHTML = '123456';
</script>
</body>
</html>
cssText
相當于width,height,background幾個屬性的簡寫。(寫成下面的形式)
box.style.cssText = 'width:300px;height:300px;background:green';
innerHTML
:設定或傳回元素之間的文本,包括元素标簽
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
a {
font-size: 20px;
}
img {
display: block;
width: 400px;
}
body {
background-image: url('./img/wallhaven-2819q9.jpg');
}
</style>
</head>
<body>
<a id="link" href="case1.html">連結</a>
<img id='img' src=".\img\wallhaven-2819q9.jpg" alt="">
<script>
var link = document.getElementById('link');
var img = document.getElementById('img');
console.log(link.href);
console.log(img.src);
console.log(link.tagName);
console.log(img.tagName);
</script>
</body>
</html>
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHLw0EVNFTSq5keRpHW4Z0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLxkzNwETM1AjMwMTNwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)