【问题标题】:Multiple buttons, each with different style - need to maintain hover state after clicked多个按钮,每个按钮都有不同的样式 - 点击后需要保持悬停状态
【发布时间】:2013-10-26 23:06:18
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你的 HTML、CSS 和 JavaScript 是什么?

标签: javascript button hover click


【解决方案1】:

鉴于完全缺乏有关您正在使用的 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() 方法的浏览器。

参考资料:

【讨论】:

    猜你喜欢
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多