1

我正在尝试实现可访问性工具,并且在单击按钮后我设法更改了段落的字体大小,但我尝试更改代码以使其适用于所有段落但不起作用

<script>

function myFunction()

{
 var p =document.getElementsByTagName('p'); // Find the element
p.style.fontSize="1.5em";          // Change the style
}
</script>

<button type="button" style="background: #ccc url(images/small.jpg);  padding: 0.3em 1em"   onclick="myFunction()"></button>

这就是它以前只对一个段落起作用的方式,但我正在尝试不止一个:

<script>
function myFunction()
{
x=document.getElementById("demo") // Find the element
x.style.fontSize="3.0em";          // Change the style
}
</script>
4

2 回答 2

3

getElementsByTagName returns a NodeList, which is like an array, so you have to loop through them and apply the style to each element:

function myFunction() {
    var arr = document.getElementsByTagName('p');
    for (var i = 0; i < arr.length; i++) {
        arr[i].style.fontSize = "1.5em";
    }
}
于 2013-02-10T15:32:25.047 回答
2

Your issue in the first code block is that getElementsByTagName returns an nodeList of elements (which you can pretend is an array). So you would need to do this:

var p =document.getElementsByTagName('p'); // Find the element
for(var i=0; i<p.length; i++) {
  p[i].style.fontSize="1.5em";          // Change the style
  }

However, a better approach would be to define some css classes to do this job for you.

<style>
body { /*normal size*/
  font-size: 1em;
}

body.largeFont {
  font-size: 1.5em;
}
</style>

<script>
function largeFont() {
  document.body.className="largeFont";
}
</script>
于 2013-02-10T15:34:22.967 回答