[英]Change cursor with getElementsByClass in JavaScript?
I want my cursor to be a hand when hovering over elements with a class of "one" after clicking a button. 在单击按钮后,将鼠标悬停在具有“ one”类的元素上时,我希望光标成为指针。 Here is my code 这是我的代码
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="JavaScript">
function cursor()
{
document.getElementByClass("one").style.cursor="pointer";
}
</script>
<h1 class="one">Mouse over this text!</h1>
</head>
<body>
<p class="fff">not me!</p>
<button type="button" onclick="cursor()">Change cursor</button>
</body>
</html>
It has only worked so far when I change it to getElementById("one") and changed one of the elements from a "one" class to a "one" id. 到目前为止,仅当我将其更改为getElementById(“ one”)并将元素之一从“一个”类更改为“一个” id时,它才起作用。 Why is this not working with class as well? 为什么这也不适用于课堂?
The reason it didn't work is because getElementsByClassName()
returns a node-list of multiple elements, which you have to access individually: 它不起作用的原因是因为getElementsByClassName()
返回了多个元素的节点列表,您必须分别对其进行访问:
function cursor() {
var elems = document.getElementByClass("one");
for (var i=0, len=elems; i<len; i++) {
elems[i].style.cursor = 'pointer';
}
}
But there really is no need to do this with JavaScript, use CSS: 但是实际上不需要使用JavaScript来执行此操作,请使用CSS:
.one {
cursor: pointer;
}
You could avoid using JavaScript here by using CSS. 您可以在此处通过使用CSS避免使用JavaScript。
.one {
cursor: pointer;
}
The reason the JavaScript didn't automatically work is because getElementById()
(if successful) returns a single reference to an element, of which you can set properties on. JavaScript无法自动运行的原因是因为getElementById()
(如果成功)返回对元素的单个引用,可以在其上设置属性。
The reason switching to getElementsByClassName()
didn't automatically work is because it returns a NodeList
, a collection of elements. 切换到getElementsByClassName()
不能自动工作的原因是因为它返回NodeList
,这是元素的集合。 This collection is like an array, and you must access its numbered properties to access the references to the elements it matched. 该集合就像一个数组,您必须访问其编号属性才能访问对其匹配的元素的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.