多个按钮,每个按钮都有不同的样式 - 单击后需要保持悬停状态
Multiple buttons, each with different style - need to maintain hover state after clicked
>我有超过 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
.
相关文章:
- 如何隐藏按钮单击事件上的占位符
- 从Web服务器下载图像按钮单击使用JavaScript
- 在SweetAlert中传递ASP.NET按钮单击事件
- 单选按钮单击可刷新/更改网站的小区域
- 调用按钮单击事件 ajax 加载的用户控件
- 附加 jQuery 代码以在加载和按钮单击时运行
- 在按钮单击时将图像URL数据显示到弹出框中,而无需禁用背景
- 按钮单击服务器单击
- 触发单选按钮单击,并在页面刷新时记住选择
- 如何使用 javascript 而不是使用控制器中的方法在 rails 中呈现部分按钮单击
- jQuery UI 选项卡 - 将参数设置为下一个/上一个按钮单击
- 如何在 Angular JS 中的按钮单击上添加类
- 当元素上有多个类时触发按钮单击事件
- 如何在 HTML 中的按钮单击上更改图像(IMG URL 每次来自服务器)
- 如何使用javascript刷新我的html页面时清除按钮单击
- 阻止后退按钮 - 单击按钮时忽略
- 如何制作按钮.单击“开始时不运行”
- Rails:尝试在按钮单击时渲染部分
- 在页面加载时调用函数,在按钮单击时再次调用函数,但参数不同
- 如何在服务器端的文本中添加按钮单击事件