<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<img src="../img/pic1.gif" alt="" width="500px"/>
<h3 id="header" class="hello" style="color: red;" title="当幸福来敲门" index="php.cn">
《当幸福来敲门》:别走,幸福终究会到来
</h3>
</body>
<script>
//1.原生属性:看做当前元素对象的属性,进行读写
var img = document.getElementsByTagName('img').item(0);
console.log(img.src); //读取原生属性
img.src="../img/pic2.jpg"; //更新属性
img.width=800;
//class属性,因为class与js中的关键字冲突,用className来表示
var h3 = document.getElementById('header');
console.log(h3.className);
//style属性 它的值不是一个字符串 是一个对象
h3.style.color="green";
//2.自定义属性
if(h3.hasAttribute('index')){ //检查属性是否存在
console.log(h3.getAttribute('index')) //查看属性
h3.setAttribute('index','当幸福来敲门') //更新属性
console.log(h3.getAttribute('index'))
h3.removeAttribute('style') //移除属性
}
//以上方法有可以用在原生属性
h3.setAttribute('style','color: yellow;font-size: 12px;');
//attributes以数组的方式来获取元素的属性 这时属性是只读的 获取的是实时更新的
console.log(h3.attributes);
console.log(h3.attributes[0]);
console.log(h3.attributes['id']);
console.log(h3.attributes['style']);
</script>
</html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号