简体   繁体   English

如何通过单击更改按钮的颜色

[英]How to change a color of a button by click

I want to change the color of a button on click I used this code but it does not work我想在单击时更改按钮的颜色我使用了此代码但它不起作用

onclick => myFunction();
function myFunction() {
  document.getElementById('#"+buttonId+"').style.color = "red";
}
function myFunction() {
  document.getElementById(buttonId).style.color = "red";
}
document.getElementById(buttonId).addEventListener('click', (event) => {
  event.target.style.color = "red";
});

addEventListerner is a better practice than using event attributes in HTML, i advise you to try with it (either if you can't use it in your situation) Also in getElementById you can't use the # caracter as CSS addEventListerner 是比在 HTML 中使用事件属性更好的做法,我建议您尝试使用它(如果您不能在您的情况下使用它)另外在 getElementById 中,您不能使用 # 字符作为 CSS

https://developer.mozilla.org/fr/docs/Web/API/EventTarget/addEventListener https://developer.mozilla.org/fr/docs/Web/API/Event https://developer.mozilla.org/fr/docs/Web/API/EventTarget/addEventListener https://developer.mozilla.org/fr/docs/Web/API/Event

Also if you want to change the color button and not only the text color, the property "color" will not be the good one, but as we don't know how your button is made, we can't really help you on this side此外,如果您想更改颜色按钮而不仅仅是文本颜色,属性“颜色”将不会是好的,但由于我们不知道您的按钮是如何制作的,因此我们无法真正帮助您边

I think buttonId is undefined or wrong.我认为buttonId未定义或错误。

Try this:尝试这个:

onclick => myFunction();

function myFunction() {
    var buttonId = 'myButton';
    document.getElementById(buttonId).style.color = "red";
}

and in the HTML:并在 HTML 中:

<button id="myButton">hello I am the button</button>

Please try this请试试这个

 function myFunction() { document.getElementById('myButton').style.color = "red"; }
 <button id="myButton" onClick="myFunction()">Change Color</button>

 const changeColor = ()=>{ const button = document.getElementById('button'); button.style.color = 'red' }
 <button id="button" onclick="changeColor()">Click me</button>

First, The Mozilla Developer Network is a great resource for DOM manipulation as can be seen here.首先,Mozilla 开发者网络是一个很好的 DOM 操作资源,可以在这里看到。 The following is a link to the MDN site:以下是 MDN 站点的链接:

https://developer.mozilla.org/en-US/docs/Web/JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript

Here is an example using the addeventlistener method from the MDN site.这是一个使用来自 MDN 站点的 addeventlistener 方法的示例。

const buttonElement = document.getElementById('btn');
buttonElement.addEventListener('click', function (event) {
  event.target.style.backgroundColor = "red";
});

First, store the id of the element that will contain the event,'btn', in a variable, then call the addEventListener() method on the buttonElement variable.首先,将包含事件的元素的 id 'btn' 存储在一个变量中,然后调用 buttonElement 变量上的 addEventListener() 方法。 The first argument, 'click', defines the event type.第一个参数“click”定义事件类型。 The second argument is a function containing the event actions.第二个参数是一个包含事件动作的函数。 Hope this helps.希望这可以帮助。

EDIT: Another user pointed out you wanted to change the background color, not the text color.编辑:另一位用户指出您想更改背景颜色,而不是文本颜色。 I misread your question, and I think most of the others did, too.我误读了您的问题,我认为其他大多数人也都读错了。 I updated my answer.我更新了我的答案。

To make it work properly you should pass de this object or the element id into your function.为了使其正常工作,您应该this对象或元素 id 传递到您的函数中。 The code would be something like this:代码将是这样的:

 function myFunction(event) { buttonId = event.id; document.getElementById(buttonId).style.color = "red"; }
 <button id='some-id' onclick=myFunction(this)> Button 1 </button> <button id='other-id' onclick=myFunction(this)> Button 2 </button>

If you want to play around with this code you can go to: https://codepen.io/mjimenezmartin/pen/MWYzNrM?editors=1111 and try different stuff.如果您想使用此代码,可以访问: https : //codepen.io/mjimenezmartin/pen/MWYzNrM?editors=1111并尝试不同的东西。


ES5-

var buttonId = document.getElementById("buttonId") // Put your button Id

buttonId.addEventListener("click", function() {
   buttonId.style.color = "red";
})


ES5+

const buttonId = document.getElementById("buttonId") // Put your button Id

buttonId.addEventListener("click", () => {
   buttonId.style.color = "red";
})

The answer is that you should use only button ID without hash mark or quotes in the getElementById.答案是在 getElementById 中应该只使用没有井号或引号的按钮 ID。 The correct line should be as follows (of course buttonId must be initialized):正确的行应该如下(当然 buttonId 必须初始化):

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

Well you got many answers, will cover few extra things.好吧,您得到了很多答案,将涵盖一些额外的内容。

rather writing concatenation like this :而是像这样编写连接:

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

you can use ES6 template literals :您可以使用 ES6 模板文字:

document.getElementById(`${buttonId}`).style.color = "red";

And to keep things simpler, i would be solving it something like this:为了让事情更简单,我会像这样解决它:

const button = document.getElementById('id');
button.onclick = ()=> { .   // you can attach event as a property as well.
 button.style.color="red";
} 

(you don't need to attach onclick attribute to your button markup this way makes mark-up much cleaner) (您不需要通过这种方式将onclick属性附加到您的按钮标记上,从而使标记更清晰)

i am not suggesting it is the best way but it is much compact.我并不是说这是最好的方法,但它非常紧凑。

Setting the colour &/or background colour is fairly straightforward using hardcoded values but does not lend itself well to re-use or template changes as you then need to edit the references to the hardcoded colours used.使用硬编码值设置颜色和/或背景颜色相当简单,但不适合重用或模板更改,因为您需要编辑对使用的硬编码颜色的引用。 Both buttons below set the same colours but the second uses a class which can have different styles depending upon whatever stylesheet happens to declare that class.下面的两个按钮设置相同的颜色,但第二个使用一个classclass可以具有不同的样式,具体取决于声明该类的任何样式表。 Neither button has an inline event handler - the preferred method is to assign event handlers externally which has similar benefits to using stylesheets ~ it keeps the HTML markup cleaner, allows for reuse and changes made in one place affect all instances if the js is within a separate file.两个按钮都没有inline事件处理程序 - 首选方法是在外部分配事件处理程序,这与使用样式表具有相似的好处~它使 HTML 标记更清晰,如果 js 在一个地方,则允许重用和更改影响所有实例单独的文件。

 document.querySelector('[name="bttn-x"]').onclick=function(e){ this.style.color='red'; this.style.backgroundColor='yellow'; } document.querySelector('[name="bttn-y"]').onclick=function(e){ this.classList.toggle('fancy'); }
 [type='button']{ padding:0.5rem; transition:all ease-in-out 500ms; } .fancy{ background:yellow; color:red; animation-name:fancybttn; animation-duration:0.5s; } @keyframes fancybttn{ from{transform:scale(1)} 30%{transform:scale(1.1)} to{transform:scale(1)} }
 <input name='bttn-x' type='button' value='Please click me' /> <input name='bttn-y' type='button' value='Or click me' />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM