如何使用html、js和css更改对象的不透明度? [英] How would i get a button to change a objects opacity with html, js & css

查看:0
本文介绍了如何使用html、js和css更改对象的不透明度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我目前使用的是选择器,因此我可以选择右下角的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。它看起来像

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
<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>

这真的是您想要的吗?还是我答错了?

这篇关于如何使用html、js和css更改对象的不透明度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆