如何使用 CSS 实现当用户悬停在列表项上时光标指向手边?
通常,如果我们将光标悬停或移动到 HTML 文档中的某个元素上,光标默认显示为箭头;如果悬停在文本上,则显示为选择器。但是,我们可以使用 CSS 属性将光标悬停在选定元素上时的行为更改为任何可用的光标类型。
现在让我们讨论并了解如何使用 :hover 状态和 CSS 的 cursor 属性更改光标悬停在任何特定元素上时的行为。
光标属性
CSS 中的 cursor 属性包含多种光标行为类型。通常,它与悬停状态一起使用,以显示光标行为的差异,并吸引用户对该元素的关注。它提供了许多光标类型选项,但在本例中,我们仅讨论将鼠标悬停在列表中的特定元素上时,将光标更改为手形光标。
默认光标可以更改为两种手形光标类型 -
Grab
Pointer
现在,让我们通过在 JavaScript 代码示例中实际实现它来详细了解它。
步骤
步骤 1 - 在第一步中,我们将使用任何类型的 HTML 列表元素创建一个包含不同项目的列表。
步骤 2 - 在下一步中,我们将为所有列表 (<li>) 元素分配一个类。
步骤3 − 在此步骤中,我们将使用上一步中提供的类来获取所有列表项,然后使用悬停状态将光标悬停到这些列表项上。
示例
以下示例将解释如何将光标悬停到特定列表项上时更改为指针 -
<html>
<head>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: aqua;
}
.list_container {
padding: 0;
background-color: bisque;
list-style: none;
}
.list_items {
padding: 5px;
border-bottom: 2px solid #444;
}
.list_items:last-child {
border-bottom: none;
}
.list_items:hover {
cursor: pointer;
}
</style>
</head>
<body>
<div class = "container">
<h3> Making the cursor to hand when a user hovers over a list item using CSS </h3>
<h4> List of a few vegatables: </h4>
<ul class = "list_container">
<li class = "list_items"> Potato </li>
<li class = "list_items"> Tomato </li>
<li class = "list_items"> Onion </li>
<li class = "list_items"> Cabbage </li>
<li class = "list_items"> Lady Finger </li>
</ul>
</div>
</body>
</html>
在上面的例子中,我们已经了解了如何在悬停于列表项上时更改光标类型。当您将鼠标悬停在任何列表项上时,光标会自动从箭头变为指针。
现在让我们再讨论一个代码示例,以实现将光标悬停于列表项上时的行为更改为抓取。
此示例的算法与上一个示例的算法相同,您只需要在列表项的悬停状态 CSS 中将光标类型从指针更改为抓取即可。
示例
以下示例将实现并将光标的行为从箭头更改为抓取,并将指针更改为-
<html>
<head>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: aqua;
}
.list_container {
padding: 0;
background-color: bisque;
list-style: none;
}
.list_items {
padding: 5px;
border-bottom: 2px solid #444;
}
.list_items:last-child {
border-bottom: none;
}
.list_items:nth-child(odd):hover {
cursor: pointer;
}
.list_items:nth-child(even):hover {
cursor: grab;
}
</style>
</head>
<body>
<div class = "container">
<h3> Making the cursor to hand when a user hovers over a list item using CSS </h3>
<h4> List of a few vegatables: </h4>
<ul class = "list_container">
<li class = "list_items"> Potato </li>
<li class = "list_items"> Tomato </li>
<li class = "list_items"> Onion </li>
<li class = "list_items"> Cabbage </li>
<li class = "list_items"> Lady Finger </li>
</ul>
</div>
</body>
</html>
以上示例将默认光标的行为从箭头更改为抓取和指针。当悬停在偶数列表项上时,光标行为将转换为抓取类型;当悬停在奇数列表项上时,光标行为将更改为指针。
总结
在本文中,我们借助代码示例实现了两种将光标从箭头更改为手形的方法。在第一个示例中,光标从箭头更改为指针;而在下一个示例中,光标在某些选定的列表项上更改为指针以及抓取。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

