首页 > 解决方案 > 我将如何获得一个现有的按钮来使用 html 更改对象的不透明度?

问题描述

我确实检查了这篇文章

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

弄清楚如何使用按钮更改对象的不透明度。我不知道如何自定义此代码以将文本的不透明度链接到现有按钮的类或 Id。

我也试过

document.getElementsByClassName("pippo1").onclick = function() {myFunction()};


function myFunction() {
  document.getElementsByClassName("text1").style.opacity = "1";
}

但它不起作用。

我可以将“更改不透明度”按钮链接到我想要自定义不透明度的文本编辑器,但我无法将现有按钮链接到此函数。

<html>

<script>

    function myFunction(button) {
       // get data-opacity
       let opacity = button.dataset.opacity;
       const el1 = document.getElementById("text1");
       const el2 = document.getElementById("text2");
       const el3 = document.getElementById("text3");
       const el4 = document.getElementById("text4");
       el1.style.opacity = "1";
       el2.style.opacity = "0";
       el3.style.opacity = "0";
       el4.style.opacity = "0";

      
     }
</script>
</head>
<body>

<button data-opacity="0" class="pippo1" onclick="myFunction(this)">PROJECT</button>
</body>
</html>

任何人都可以帮忙吗?

谢谢

埃琳娜

标签: javascripthtmlcss

解决方案


试试这个,你可以使用classListto或CSSaddremovetoggleclasses

const button = document.getElementById("button");
const div = document.getElementById("div");

button.addEventListener("click", myfun);

function myfun(){
  div.classList.add("fadeout");
}
#div{ width:100px;height:100px;background-color:blue; 
transition:0.5s; }
.fadeout{ opacity:0; visibility:hidden; }
<button id="button">Fade</button>
<br>
<div id="div"></div>


推荐阅读