为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript 按钮 onclick 更改

Javascript 按钮 onclick 更改

HUX布斯 2021-10-29 10:42:21
我需要制作一个按钮,当点击执行一个功能,然后在更改之后,就好像它是一个开/关按钮一样,它在每个与 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>
查看完整描述

2 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

不确定“仅使用纯 JS”classList.toggle()是什么意思,但对此非常有用。我还建议您将样式保留在 CSS 中,而不是 JS 或 HTML。


const buttonElement = document.querySelector('.js-toggle-button')

const paragraphElement = document.querySelector('.js-paragraph')


buttonElement.addEventListener('click', () => {

  paragraphElement.classList.toggle('paragraph--off')

})

.paragraph {

  color: red;

}


/* Overrides because of specificity */

.paragraph--off {

  color: blue;

}

<p class="js-paragraph paragraph">Paragraph</p>

<button class="js-toggle-button">Toggle</button>


查看完整回答
反对 回复 2021-10-29
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

我修改了你的 jsfidle检查这个


let firstCall = true;

function mudarred(){

    if(firstCall){

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

        firstCall= false;

    }else{

        firstCall=true;

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

    }

}


查看完整回答
反对 回复 2021-10-29
  • 2 回答
  • 0 关注
  • 146 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信