我将如何获得一个按钮来使用html,js和css更改对象的不透明度

问题描述

我想创建一个按钮来隐藏我的网站登录页面的天气部分,但我不知道该怎么做!

Image

我当前使用的是“选择器”,因此我可以选择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: nonedisplay: block显示和隐藏天气div。以下代码将解决将解决您的问题。

<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>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...