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

时间:2013-10-26 23:06:19

标签: javascript button hover click

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

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

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

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

1 个答案:

答案 0 :(得分:0)

鉴于完全没有关于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 Fiddle demo

以上内容基于以下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属性,以及节点的addEventListener()方法。

参考文献: