Javascript:点击后更改元素的样式(Javascript: change styles of elements upon clicking)

编程入门 行业动态 更新时间:2024-10-23 09:21:23
Javascript:点击后更改元素的样式(Javascript: change styles of elements upon clicking)

这是我写的一些Javascript:

function toggle(clicked_id) { // Change last button back to light gray. if (typeof last_id !== 'undefined') { document.getElementById(last_id).style.opacity = '.35'; } // Change current button to dark gray. document.getElementById(clicked_id).style.opacity = '1'; last_id = clicked_id; }

这是HTML:

<div class="circle" onClick="toggle(this.id)" id="button1"></div> <div class="circle" onClick="toggle(this.id)" id="button2"></div> <div class="circle" onClick="toggle(this.id)" id="button3"></div>

而CSS:

.circle { background: black; width: .625em; height: .625em; border-radius: 50%; margin-bottom: .35em; opacity: .35; } .circle:hover { opacity: 1; cursor: pointer; }

有3个按钮,每个按钮的不透明度为“.35”。 悬停在按钮上时,其不透明度变为“1”。 如您所见,这部分是用CSS完成的。 到现在为止还挺好。 我现在想要的是在单击按钮时将按钮的不透明度永久性地更改为“1”。 它应该保持这样,直到我点击另一个按钮,此时它将返回'.35'并且新按钮将为'1'。

我试图用Javascript实现这一点,但我无法弄清楚为什么我的代码不起作用。 请看看我的JSFiddle 。

PS我为每个按钮分配了一个特定的id,但我宁愿不在样式表中定义它们。

Here is some Javascript I've written:

function toggle(clicked_id) { // Change last button back to light gray. if (typeof last_id !== 'undefined') { document.getElementById(last_id).style.opacity = '.35'; } // Change current button to dark gray. document.getElementById(clicked_id).style.opacity = '1'; last_id = clicked_id; }

Here is the HTML:

<div class="circle" onClick="toggle(this.id)" id="button1"></div> <div class="circle" onClick="toggle(this.id)" id="button2"></div> <div class="circle" onClick="toggle(this.id)" id="button3"></div>

And the CSS:

.circle { background: black; width: .625em; height: .625em; border-radius: 50%; margin-bottom: .35em; opacity: .35; } .circle:hover { opacity: 1; cursor: pointer; }

There are 3 buttons, with an opacity of '.35' each. Upon hovering on a button its opacity changes to'1'. As you can see, this part is done with CSS. So far so good. What I want now is to permanently change a button's opacity to '1' when it is clicked. It should stay like that until I click another button, at which point it will go back to '.35' and the new button will be at '1'.

I've tried to achieve this with Javascript but I can't figure out why my code doesn't work. Please take a look at my JSFiddle.

P.S. I have assigned a specific id to each button, but I would rather not define these in the stylesheet.

最满意答案

我将创建一个具有不透明度1的新CSS类,并且onClick更改被单击的对象的类,并从该对象中删除.circle类。

I would create a new CSS class with opacity 1 and onClick change the class of the object that was clicked, and remove the .circle class from that object.

更多推荐

本文发布于:2023-07-31 18:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1347258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:样式   元素   Javascript   change   clicking

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!