单击后更改按钮样式

时间:2016-06-12 23:14:01

标签: javascript html css

我想要一个按钮,在点击它之后改变它的外观,让它保持这种状态。我已经尝试使用"按钮:焦点"并且它可以工作,但只要点击另一个按钮或任何其他按钮,任何先前选择的按钮将重新回到它的原始样式。

我有默认的样式设置和悬停样式设置,但无法保持访问/点击的样式。我不想让它回到页面重新加载之前。这是你可以用css做的事情,必须用JS实现吗?

这将有点冗长,但到目前为止我已经拥有了:

HTML:

<div style="text-align:center;">
  <button id=p1Button><span>Player One, please select me! </span></button>
  <button id=p2Button><span>Player Two, please select me! </span></button>
</div>

CSS:

button{
  width: 16em;
  color: white;
  background: #0392CF;
  font-weight: 800;
  font-size: 1.5em;
  background-attachment: fixed;
  border-radius: .25em;
  cursor: pointer;
  border: none;
  margin: .5;
  height: 2.2;
  transition-duration: 1.5s;
  transition-timing-function: linear;
}
button:hover {
  color: white;
  background: #F37736;
  border-radius: 2em;
  width: 13em;
}
button:hover span {
  display: none;
}
button:hover:before {
  content:"Clicky Clicky!";
  letter-spacing: .25em;
}
button:focus {
  color: white;
  background: #F37736;
  border-radius: 2em;
  width: 13em;
}
button:focus span {
  display: none;
}
button:focus:before {
  content:"Clicked!";
  letter-spacing: .25em;
}

2 个答案:

答案 0 :(得分:1)

你需要了解焦点是一个阶段。每当元素失去焦点时,它将变回旧样式。您想要达到的目标是由“点击”事件触发。使用JS是处理它的最佳方式。

document.getElementById('p1Button').addEventListener('click', onClick);
document.getElementById('p2Button').addEventListener('click', onClick);

function onClick(){
    this.className += ' YourClassHere';
}

我还建议您使用jQuery,这应该更方便。

答案 1 :(得分:1)

最好的方法是使用JavaScript。更简单的方法是使用jQuery。

在js文件中,使用以下代码来执行jQuery

$("#p1Button").click(function(){
    $(this).addClass("yourClassName");
});

如果您不想使用jQuery,那么请使用以下代码并在HTML中提供对该函数的引用,如<button onclick="clickedOnButton(this)" id=p1Button><span>Player One, please select me! </span></button>

function clickedOnButton(this)
{
    this.className+='yourClassName';
}

在css文件中添加一个类

.yourClassName
{
   /* Style to use when clicked on button. */
}
相关问题