Javascript getElementById 然后计算长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14478717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getElementById then calculate length
提问by cloggy
A fairly easy question I assume, but I'm only a beginner and I'm struggling to work this out for myself and I can't seem to find the answer on google.
我假设一个相当简单的问题,但我只是一个初学者,我正在努力为自己解决这个问题,我似乎无法在谷歌上找到答案。
I have a heading tag that I need to grab using javascript and then work out the length of, then edit the font size depending on the result.
我有一个标题标签,我需要使用 javascript 抓取它,然后计算出它的长度,然后根据结果编辑字体大小。
Why is my code not working?
为什么我的代码不起作用?
var titleElement = document.getElementById("myelement");
if(titleElement.length>10){
titleElement.style.fontSize = 16;
}
EDIT / ADDITION
编辑/添加
I can't get it to work, even after your kind suggestion to add .innerHTML:
即使在您提出添加 .innerHTML 的善意建议之后,我也无法让它工作:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="titleLengthShow()">
<h1 id="myelement">dfg adg earsh aaerg eaag erg aergethj5 yetfgg eg d</h1>
<script type="text/javascript">
function titleLengthShow(){
var titleElement = document.getElementById("myelement");
if(titleElement.innerHTML.length>10){
titleElement.style.fontSize = 16;
}
}
</script>
</body>
</html>
回答by Christian
var titleElement = document.getElementById("myelement");
if(titleElement.innerHTML.length > 10){
titleElement.style.fontSize = "16px";
}
should work. innerHTML gives you the containing text (actually html).
应该管用。innerHTML 为您提供包含文本(实际上是 html)。
if you have formating inside your heading tag it will also count those formating tags. instead you can use .textContent instead of .innerHTML, although this won't work in older IEs. for older IE versions .innerText should work.
如果您的标题标签中有格式,它也会计算这些格式标签。相反,您可以使用 .textContent 而不是 .innerHTML,尽管这在较旧的 IE 中不起作用。对于较旧的 IE 版本 .innerText 应该可以工作。
var length = (titleElement.textContent || titleElement.innerText ||
title.innerHTML).length;
shoudl work for the common browsers.
应该适用于常见的浏览器。
回答by user1954492
change
改变
if(titleElement.length>10){
titleElement.style.fontSize = 16;
}
to
到
if(titleElement.innerHTML.length> 10){
titleElement.style.fontSize = "16px";
}
回答by Bernhard
You need to check the length of titleElement.innerHTML.
您需要检查titleElement.innerHTML.
I strongly suggest to look into jQuery to do such things.
我强烈建议研究 jQuery 来做这样的事情。

