【问题标题】:Change :active pseudo-class' style with jQuery用 jQuery 改变 :active 伪类的样式
【发布时间】:2015-03-29 06:20:16
【问题描述】:

我正在开发一些 CSS 编辑器,并希望能够在单击 <button> 时更改其样式。以下代码不会将background-color 更改为黄色。

http://jsfiddle.net/65erbrhh/

$('a').click(function() {
    event.preventDefault();
    $('button:active').css('background-color', 'yellow');
});

编辑:就我而言,我无法为按钮分配特定的类,因为它是用户可自定义的 html。

【问题讨论】:

  • 那么如何在您的案例中停用按钮? css?
  • 无需停用,:active状态可以使用相同的颜色

标签: javascript jquery html css


【解决方案1】:

由于您无法根据 CSS 状态选择元素,因此一种选择是向元素添加一个类:

Updated Example

$('a').click(function (e) {
    e.preventDefault();

    $('button').addClass('active-style');
});
button.active-style:active {
    background-color: yellow;
}

但是既然你说你不能这样做,你也可以为 mousedown/mouseup 事件附加一个事件监听器并相应地更改背景颜色:

Updated Example

$('a').click(function () {
    event.preventDefault();

    $('button').on('mousedown mouseup', function (e) {
        $(this).css('background-color', e.type === 'mousedown' ? 'yellow' : '');
    });
});

..但如果您希望示例在mouseup button 元素之外 工作,则需要收听all mouseup事件:

Updated Example

$('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);
});

【讨论】:

  • 在您的代码中,您的目标是button on mouseupon mouse down,而他想要的是a
  • 这适用于 jsfiddle 示例,但是有一个有趣的例外,我应该在我的 OP 中提到这一点。如果我使用 jQuery 为 button 应用常规样式,它会忽略一般 css 定义中指定的样式。 jsfiddle.net/feq71wdh/1。这是不相关的问题,但它困扰我。 =)
  • @AlexG 是的,那是因为 jQuery 的 .css() 方法添加了内联 CSS,它在样式表中始终具有比 CSS 更高的 specificity..(除非使用 !important,这是不鼓励的。 )
  • @JoshCrozier:实现:$(this).css('cssText', event.type === 'mousedown' ? cssProperty + ': ' + hex + ' !important' : ''); 并且它有效,除了“边框颜色”。你知道可能是什么问题吗?感谢您的帮助。
  • @JoshCrozier: 没关系,通过在 jQuery 中复制 border-width: 1px 来修复,如果我用 jQuery 设置 1 个属性,显然所有以前的属性都将被忽略
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 2021-06-01
  • 2011-03-30
  • 1970-01-01
相关资源
最近更新 更多