多个按钮,每个按钮都有不同的样式 - 单击后需要保持悬停状态

Multiple buttons, each with different style - need to maintain hover state after clicked

本文关键字:按钮 单击 状态 悬停 样式      更新时间:2023-09-26

>我有超过 3 个按钮,每个按钮都有不同的样式(不同的边框颜色,悬停时不同的背景颜色)。(我用<li>创建了它们,因为它们具有更改图片背景位置的操作)。

我希望它们在单击后保持相同的悬停状态外观,但在单击另一个按钮时恢复正常状态。

我该怎么做?提前谢谢你:)

ps:我在需要时使用 css、js 使用 HTML(就像在这种情况下一样)。

鉴于完全缺乏有关 HTML 和您正在使用的当前 JavaScript 的信息,我能提供的最好的就是简单演示如何实现这一点:

function colorify (e) {
    // get a reference to the element we're changing/working on:
    var demo = document.getElementById('demo'),
        /* getting the siblings, the other controls,
           of the clicked-element (e.target):
        */
        controls = e.target.parentNode.children;
    // iterating over those controls
    for (var i = 0, len = controls.length; i < len; i++) {
        /* if the current control[i] is the clicked-element, we 'add' the 'active'
           class, otherwise we 'remove' it (using a ternary operator):
        */
        controls[i].classList[controls[i] == e.target ? 'add' : 'remove']('active');
    }
    /* changing the background-color of the 'demo' element, setting it to the
       textContent of the clicked-element:
    */
    demo.style.backgroundColor = e.target.textContent;
}
var controls = document.getElementById('controls');
controls.addEventListener('click', colorify);

JS小提琴演示。

以上基于以下 HTML:

<div id="demo"></div>
<ul id="controls">
    <li>Red</li>
    <li>Green</li>
    <li>Blue</li>
</ul>

和 CSS:

#demo {
    width: 10em;
    height: 10em;
    border: 2px solid #000;
}
.active {
    color: #f00;
}

此方法需要一个实现 classList API、DOM 节点的 children 属性以及 Node 的addEventListener()方法的浏览器。

引用:

  • addEventListener .
  • Element.classList .
  • ParentNode.children .