默认情况下如何使按钮处于活动状态?

时间:2020-10-06 09:32:11

标签: javascript css button

我有一个如下所示的按钮-我希望它默认处于“悬停”和“焦点”模式-默认情况下,游戏以“简单”开始,因此我希望默认情况下为“按下”按钮我可以在课堂上做到这一点-我该怎么做?

<button id="easyBtn"">Easy</button>

与我的课程一起

.buttons button {
  background-color: #03A9F4;
  border: none;
  padding: 5px 10px;
  text-transform: uppercase;
  color: white;
  font-weight: 700;
  border-radius: 3px;
}

.buttons button:hover, button:focus {
  background-color: #0074a9;
  outline: none;
}

2 个答案:

答案 0 :(得分:1)

我认为您会发现单选按钮更适合此工作。您可以根据需要设置按钮的样式。下面是我对解决方案的看法

var currentDifficulty = 'easy';

function onDifficultyChange(e) {
    currentDifficulty = e.value;
    console.log(currentDifficulty);
}
    [type='radio'] {
        display: none;
    }
    [type='radio'] ~ span {
        padding: 8px 16px;
        border: solid 1px royalblue;
    }
    [type='radio']:checked ~ span {
        background: royalblue;
        color: white;
    }
<label>
    <input
        type="radio"
        name="difficulty"
        value="easy"
        checked
        onchange="onDifficultyChange(this)"
    />
    <span>Easy</span>
</label>
<label>
    <input
        type="radio"
        name="difficulty"
        value="medium"
        onchange="onDifficultyChange(this)"
    />
    <span>Medium</span>
</label>
<label>
    <input
        type="radio"
        name="difficulty"
        value="hard"
        onchange="onDifficultyChange(this)"
    />
    <span>Hard</span>
</label>

答案 1 :(得分:0)

由于您必须将游戏难度存储为变量,因此可以在游戏初始化函数中运行以下操作:

document.getElementById(`button-${gameDifficulty}`).focus();

但是就像线程中提到的某人一样,单选按钮似乎在这里更合适。

相关问题