我如何使用 html、js 和 css 获得更改对象不透明度的按钮

How would i get a button to change a objects opacity with html, js & css

我想制作一个按钮来隐藏我网站登录页面的天气部分,但我不知道如何制作!

我目前使用“selector”,所以我可以 select 01,您可以在右下角看到它,并且效果很好但我更喜欢一个按钮。这是我当前使用的代码:

</div>
  <div class="wopacity">
   <select onchange="myFunction(this);" size="2">
   <option>0
   <option selected="selected">1
   </select>

   <script>
    function myFunction(x) {
     // Return the text of the selected option
     var opacity = x.options[x.selectedIndex].text;
     var el = document.getElementById("p1");
     if (el.style.opacity !== undefined) {
       el.style.opacity = opacity;
     } else {
       alert("Your browser doesn't support this example!");
     }
    }
   </script>
  </div>

如果你想使用一个按钮,你可以在按钮上添加一个data-* attribute。它看起来像

<html>
<head>
<script>
    function myFunction(button) {
       // get data-opacity
       let opacity = button.dataset.opacity;
       const el = document.getElementById("p1");
       el.style.opacity = opacity;

       /* shorthand for
            if (opacity === "1") {
              button.dataset.opacity === "0";
            else {
              button.dataset.opacity === "1";
            }
       */
       button.dataset.opacity = opacity === "1" ? "0" : "1";
     }
</script>
</head>
<body>
<div id="p1">Opacity test</div>
<button data-opacity="0" onclick="myFunction(this)">Change opacity</button>
</body>
</html>

这真的是你想要的还是我问错了?

您可以创建一个按钮并使用 javascript 获取它,然后使用 CSS 属性 display: none 或 [= 显示和隐藏天气 div 12=]。以下代码将解决将解决您的问题。

<html>
 <head>
  <script>
  function myFunction(button) {
   const ele = document.getElementById("weatherElem");
   el.style.display = el.style.display === "none" ? "block" : "none";
 }
 </script>
  <div id="weatherElem">Weather Element</div>
  <button id="button" onclick="myFunction(this)">Toogl weather</button>
 </body>
</html>