Ale*_*x G 2 html javascript css jquery
我正在开发一些 CSS 编辑器,并希望提供<button>在单击时更改样式的功能。以下代码不会更改background-color为黄色。
$('a').click(function() {
event.preventDefault();
$('button:active').css('background-color', 'yellow');
});
Run Code Online (Sandbox Code Playgroud)
编辑:就我而言,我无法将特定类分配给按钮,因为它是用户可自定义的 html。
由于您无法根据 CSS 状态选择元素,因此一种选择是向元素添加一个类:
$('a').click(function (e) {
e.preventDefault();
$('button').addClass('active-style');
});
Run Code Online (Sandbox Code Playgroud)
button.active-style:active {
background-color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
但是既然你说你不能这样做,你也可以为mousedown/mouseup事件附加一个事件侦听器并相应地更改背景颜色:
$('a').click(function () {
event.preventDefault();
$('button').on('mousedown mouseup', function (e) {
$(this).css('background-color', e.type === 'mousedown' ? 'yellow' : '');
});
});
Run Code Online (Sandbox Code Playgroud)
..但是如果您希望示例在元素mouseup 之外工作,则button需要侦听所有 mouseup事件:
$('a').click(function (e) {
e.preventDefault();
$('button').addClass('active-style');
});
$(document).on('mousedown mouseup', function (e) {
var color = (e.type === 'mousedown' && $(e.target).hasClass('active-style')) ? 'yellow' : '';
$('button.active-style').css('background-color', color);
});
Run Code Online (Sandbox Code Playgroud)