使用 CSS 和 JavaScript 隐藏网页上的光标

PHPz
PHPz 转载
2023-09-17 19:53:03 285浏览

使用 CSS 和 JavaScript 隐藏网页上的光标

在本教程中,我们将学习使用 CSS JavaScript 在网页中隐藏光标。有时,我们需要创建样式光标,然后需要隐藏光标。也许它还需要隐藏特定 HTML 元素的光标。

有两种方法可以隐藏网页上的光标。一种使用 CSS,另一种使用 JavaScript。我们将在本教程中一一学习这两种方法。

使用CSS隐藏网页上的光标

CSS 允许我们更改光标的样式。我们可以使用 CSS 创建不同类型的光标。如果我们不想显示光标,我们可以将样式“cursor: none”应用于特定的 HTML 元素。

语法

用户可以按照以下语法使用 CSS 隐藏光标。

CSS Selector {
   cursor: none;
}

示例

在此示例中,我们创建了 div 元素并指定了正确的高度和宽度。此外,我们还使用 CSS 将红色背景颜色应用于 div。之后,我们将 class 属性添加到 div 元素并使用“test”值对其进行初始化。

我们在 CSS 中使用测试类名称作为 CSS 选择器,并将“cursor: none”样式应用于 div 元素。

<html>
<head>
   <style>
      .test {
         /* style to hide the cursor */
         cursor: none;
         height: 300px;
         width: 300px;
         background-color: red;
      }
   </style>
</head>
<body>
   <h2>
      Hiding the cursor using <i> CSS. </i>
   </h2>
   <!-- hiding the cursor in this div element -->
   <div class="test">Hiding the cursor for this div.</div>
</body>
</html> 

在上面的输出中,用户可以观察到当用户将光标移入 div 元素时光标消失。

使用JavaScript隐藏网页上的光标

我们可以使用JavaScript 来更改任何HTML 元素的样式。每个 HTML 元素都包含 style 属性,我们可以通过将 HTML 元素作为引用来访问该属性。之后,我们可以访问 style 属性的特定样式属性并更改其值。在这里,我们将使用 JavaScript 将 cursor 属性的值更改为 none。

语法

用户可以按照以下语法使用 JavaScript 隐藏网页上的光标。

let testDiv = document.getElementById("test");
testDiv.style.cursor = "none"; 

在上面的语法中,styletestDiv元素的属性,光标是style对象的属性。我们将光标属性的值更改为“none”。

示例

在下面的示例中,我们通过

<html>
<head>
   <style>
      .test {
         height: 300px;
         width: 300px;
         background-color: blue;
      }
   </style>
</head>
<body>
   <h2>Hiding the cursor using <i>JavaScript.</i></h2>
   <div class="test" id="test">Hiding the cursor for this div.</div>
   </br>
   <button onClick="HideCursor()">Hide cursor on Div</button> 
   <script>
      
      // Accessing the HTML element by id
      let testDiv = document.getElementById("test");
      function HideCursor() {
         
         // hiding the cursor
         testDiv.style.cursor = "none";
      }
   </script>
</body>
</html>

在上面的输出中,当用户单击“在 Div 上隐藏光标”按钮时,它会隐藏 div 元素上的光标。

我们学习了两种将光标隐藏在网页上特定 HTML 元素上的方法。用户可以根据自己想要从 CSS 还是 JavaScript 更改光标样式来使用其中一种方式。

以上就是使用 CSS 和 JavaScript 隐藏网页上的光标的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除