Javascript 按钮 onclick 更改

我需要制作一个按钮,当点击执行一个功能,然后在更改之后,就好像它是一个开/关按钮一样,它在每个与 css 一起使用的按钮中执行 2 个功能 1,并且仅使用纯 javascript


<!DOCTYPE html>

<html>


<head>


</head>


<body>

<p id="red"> Paragrafo 01</p>





<input type="button" 

 value= "cor" onclick="mudarred();" />


 <script>

    function mudarred(){

  if()

        document.getElementById('red').style.color="red";

    else

    document.getElementById('red').style.color="blue";


    }


    </script>


</body>

</html>


HUX布斯
浏览 147回答 2
2回答

繁花如伊

不确定“仅使用纯 JS”classList.toggle()是什么意思,但对此非常有用。我还建议您将样式保留在 CSS 中,而不是 JS 或 HTML。const buttonElement = document.querySelector('.js-toggle-button')const paragraphElement = document.querySelector('.js-paragraph')buttonElement.addEventListener('click', () => {&nbsp; paragraphElement.classList.toggle('paragraph--off')}).paragraph {&nbsp; color: red;}/* Overrides because of specificity */.paragraph--off {&nbsp; color: blue;}<p class="js-paragraph paragraph">Paragraph</p><button class="js-toggle-button">Toggle</button>

有只小跳蛙

我修改了你的 jsfidle检查这个let firstCall = true;function mudarred(){&nbsp; &nbsp; if(firstCall){&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('red').style.color="red";&nbsp; &nbsp; &nbsp; &nbsp; firstCall= false;&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; firstCall=true;&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('red').style.color="blue";&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript