我是 JavaScript 新手。我有一个 html 文档,我想更改 div 内段落的字体大小,但遇到问题。我在控制台中收到此错误:
Uncaught TypeError: Cannot set property 'fontSize' of undefined codigo.js:5
这是我的 html:
<!DOCTYPE html>
<html leng="es">
<head>
<meta charset="UTF-8">
<title>Mi ejercicio DHTML</title>
<link rel="stylesheet" type="text/css" href="css/estilos.css">
<script type="text/javascript" src="js/codigo.js" ></script>
</head>
<body>
<div id="parrafos">
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
<p>
Your bones don't break, mine do. That's clear. Your cells react to bacteria
</p>
</div>
</body>
</html>
这是我的js:
window.addEventListener('load', inicio);
function inicio(){
var parrafos = document.getElementById('parrafos');
parrafos.childNodes[0].style.fontSize='10px';
}
我想要的是使用名为 parrafos
的 div 上的 childNodes通过访问其索引 parrafos.childNodes[2].style....
更改每个段落的样式等等等等
[编辑]
我以这段代码结束:
window.addEventListener('load', inicio);
function inicio(){
var parrafos = document.getElementById('parrafos');
parrafos.childNodes[1].style.fontSize='1.5em';
parrafos.childNodes[3].style.fontSize='1.3em';
parrafos.childNodes[5].style.fontSize='.5em';
parrafos.childNodes[7].style.fontSize='1em';
parrafos.childNodes[9].style.fontSize='.2em';
}
我发现由于 html 文档中的空格,它不遵循连续的顺序,这看起来很奇怪,因为我认为它应该连续。
最佳答案
试试这个:
window.addEventListener('load', inicio);
function inicio(){
var parrafos = document.getElementById('parrafos');
for (var i=0; i<parrafos.children.length; i++) {
parrafos.children[i].style.fontSize = '10px';
}
}
关于javascript - 在 JavaScript 中使用 childNode 更改段落样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15644137/