简体   繁体   English

使用JavaScript更改ul元素的字体大小

[英]Change font size of ul element using javascript

Here is the css: 这是CSS:

#content ul {
               font-size: 12px;
           }

I am trying this: 我正在尝试:

document.getElementById("content ul").style.fontSize = 8px;

But this is not working for me. 但这对我不起作用。 Can anybody suggest how to do this? 有人可以建议如何做吗?

Two issues: 两个问题:

  1. Style properties are strings, so you need "8px" rather than 8px . 样式属性是字符串,因此您需要"8px"而不是8px

  2. getElementById gets elements by ID . getElementById 通过ID获取元素。 You're passing in a compound selector (and you're missing the # from it). 您传入了复合选择器(并且缺少其中的# )。 You'll have to use an ID and then find the children (via getElementsByTagName ), or use querySelector (for the first matching element) or querySelectorAll (for all matching elements) instead. 您必须使用ID,然后找到子项(通过getElementsByTagName ),或者使用querySelector (对于第一个匹配元素)或querySelectorAll (对于所有匹配元素)代替。 (Note that although well-supported in general, some older browsers don't have those last two; details .) (请注意,尽管总体上得到了很好的支持,但是某些较旧的浏览器没有最后两个; 详细信息 。)

So for instance, here's how you would change the first matching element's font size on browsers with querySelector support: 因此,例如,这是在带有querySelector支持的浏览器中如何更改第一个匹配元素的字体大小的方法:

document.querySelector("#content ul").style.fontSize = "8px";

Or all of them 或全部

var list = document.querySelectorAll("#content ul");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].style.fontSize = "8px";
}

Or on older browsers: 或在较旧的浏览器上:

var content = document.getElementById("content");
var list = content.getElementsByTagName("ul");
var index;
for (index = 0; index < list.length; ++index) {
    list[index].style.fontSize = "8px";
}

<ul>'s are elements, not id's. <ul>'s是元素,而不是id。 Get the content element by id first. 首先通过id获取content元素。 Then get child nodes inside that are unordered lists. 然后,在其中获得无序列表的子节点。 Finally iterate over the list and change the size. 最后遍历列表并更改大小。 And as TJ said, you need to pass in a string. 正如TJ所说,您需要输入一个字符串。

var lists = document.getElementById('content').getElementsByTagName('ul');
for (var i; i < lists.length; i++ ) {
     lists[i].style.fontSize = '8px';
}

You need to select them properly. 您需要正确选择它们。 First you need to get the element that contains the <ul> in question. 首先,您需要获取包含有问题的<ul>的元素。

var contentArea = document.getElementById("content");

Then you need to get the appropriate tags by tagname: 然后,您需要按标记名获取适当的标记:

var tags = contentArea.getElementsByTagName("ul");

Then cycle through them to set the font size: 然后循环浏览以设置字体大小:

for (i=0; i<tags.length, i++)
{
    tags[i].style.fontSize = "8px"; // Don't forget the " here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM