如何使用 CSS 设置分区元素的不透明度?

cssweb developmentfront end technology更新于 2025/1/30 11:24:17

style.opacity 属性用于设置元素的不透明度,并返回字符串值。该属性用于设置或返回不同 HTML 元素的不透明度。它是 HTML 样式不透明度属性之一。

onclick 事件仅在用户点击元素时发生,它是一个纯 JavaScript 属性。每当您点击 onclick 事件时,它都会执行一些操作,例如显示消息或将用户重定向到另一个页面。onclick 事件在网站中应尽量少用,因为它可能会让用户感到困惑。因此,请明智地使用这些事件。

语法

以下是使用 JavaScript 设置不透明度的语法 -

object.style.opacity = "number|initial|inherit"

参数

  • number - 用于指定不透明度

示例

在此示例中,我们将使用 CSS 设置分区元素的不透明度。

<html> 
   <head>
      <style>
         #content {
            color: blue;
            font-weight: lighter;
            font-size: 20px;
            text-align: center;
         }
         #op{
            opacity: 0.3;
            text-align: center;
         }
      </style>
   </head>
   <body>
      <h2>Setting the opacity level for division element using the CSS</h2>
      <h3 id="content">Tutorial Point</h3>
      <div id="op">
         Example program for the Opacity Level
      </div>
   </body>
</html>

使用 JavaScript 更改分区元素的不透明度

请按照以下步骤使用 JavaScript 设置分区元素的不透明度 -

步骤 1 - 让我们定义 HTML 文档的标题和 div 元素的样式,这将设置 div 元素的不透明度。对于 h3 元素,我们定义了颜色、字体粗细、字体大小和文本对齐。对于 div 元素,我们定义了文本对齐。

步骤 2 - 在 body 部分下,我们定义了标题、div、按钮和脚本元素。

步骤 3 - 对于按钮元素,定义 opacityFun() 方法。使用此方法可以更改不透明度级别。

步骤 4 − 在 opacityFun() 方法中,明确指出了应执行哪个方法功能的 id。

步骤 5 − style opacity 属性是 HTML DOM 属性,用于设置不透明度级别。

步骤 6 − 点击按钮后,将触发 onClick 事件函数,并设置 div 元素的不透明度。

示例

在此示例中,我们将使用 JavaScript 设置 div 元素的不透明度级别。

<html> 
   <head>
      <style>
         .heading {
            color: violet;
            font-weight: bolder;
            font-size: 18px;
            text-align: center;
         }
         #div1 {
            text-align: center;
         }
      </style>
   </head>
   <body> 
      <h2>Setting the opacity level for division element using the JavaScript</h2>
      <h3 class="heading">Tutorix</h3>
      <div id="div1">
         Example program for the Opacity Level
      </div>
      <br></br>
      <button type="button" onclick="opacityFun()">
      Click Here to set the opacity
   </body> 
   <script>
      function opacityFun() {
         document.getElementById("div1").style.opacity = "0.2";
      }
   </script>
</html>

结论

本文通过示例演示了如何设置 div 元素的不透明度。我们在这里看到了两个不同的示例。在第一个示例中,我们使用简单的 CSS 设置了 div 元素的不透明度。在第二个示例中,我们使用 JavaScript 更改了 div 元素的不透明度。在这里,我们使用了 onclick 事件和 style opacity 属性来更改不透明度。


相关文章


有用资源