[英]Why getElementsByClassName does not work?
I'm trying to detect screen resolution then set position (like top,left) for multiple screen resolution,but it's not working. 我正在尝试检测屏幕分辨率,然后为多个屏幕分辨率设置位置(例如顶部,左侧),但是它不起作用。 Anyone knows what's wrong with my code?
有人知道我的代码有什么问题吗?
CSS: CSS:
.Scrolloutside
{
position:relative;
left: 550px;
}
javascript: JavaScript的:
var nHeight = screen.height;
var nWidth = screen.width;
if (nHeight ==714 && nWidth==1005)
{
//document.write("height:"+nHeight+" ,width="+nWidth+"<br>");
var newsTarget = document.getElementsByClassName('Scrolloutside');
newsTarget.style.top= "500px";
}
html: HTML:
<div class = "Scrolloutside">
<div class="scroller_title">News</div>
<div class="scroller_container">
<div class="jscroller2_up">
<?
echo $secnews;
?>
</div>
</div>
</div>
</div>
document.getElementsByClassName()
returns a nodeList
or HTMLCollection
which are both a list of elements, not a single element. document.getElementsByClassName()
返回一个nodeList
或HTMLCollection
,它们都是元素列表,而不是单个元素。 Even if there is only one matching element, it still returns a list with just one item in it. 即使只有一个匹配元素,它仍会返回仅包含一项的列表。 As such, you have to either get the first item in the list or iterate through the whole list (depending upon what your code wants).
因此,您必须获取列表中的第一项,或者遍历整个列表(取决于您的代码需要什么)。
Get the first item from the list (if you can assume there's only one item with the class name): 从列表中获取第一项(如果您可以假设只有一个具有类名的项):
var newsTarget = document.getElementsByClassName('Scrolloutside');
newsTarget[0].style.top= "500px";
or iterate through the list (if there may be more than one item with that class name): 或遍历列表(如果可能有多个具有该类名称的项目):
var newsTarget = document.getElementsByClassName('Scrolloutside');
for (var i = 0; i < newsTarget.length; i++) {
newsTarget[i].style.top= "500px";
}
Use as 用于
newsTarget[0].style.top= "500px";
The getElementsByClassName()
method returns a collection of all elements in the document with the specified class name, as a NodeList object. getElementsByClassName()
方法以NodeList对象的形式返回文档中具有指定类名的所有元素的集合。
The NodeList object represents a collection of nodes. NodeList对象代表节点的集合。 The nodes can be accessed by index numbers.
可以通过索引号访问节点。 The index starts at 0
索引从0开始
在页面底部使用它。
newsTarget[0].style.top= "500px";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.