javascript - Change :active pseudo-class' style with jQuery - Stack Overflow

I'm developing some CSS editor and want to provide ability to change style for <button> when

I'm developing some CSS editor and want to provide ability to change style for <button> when it's clicked. The following code doesn't change background-color to yellow.

/

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

Edit: In my case, I can't assign specific class to a button, because it's user customizable html.

I'm developing some CSS editor and want to provide ability to change style for <button> when it's clicked. The following code doesn't change background-color to yellow.

http://jsfiddle/65erbrhh/

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

Edit: In my case, I can't assign specific class to a button, because it's user customizable html.

Share Improve this question edited Mar 28, 2015 at 22:20 Josh Crozier 242k56 gold badges400 silver badges313 bronze badges asked Mar 28, 2015 at 0:19 scorpio1441scorpio1441 3,08810 gold badges41 silver badges79 bronze badges 2
  • So how do you deactivate a button in your case? css? – callback Commented Mar 28, 2015 at 0:32
  • There is no need to deactivate, user can use same colors for :active state – scorpio1441 Commented Mar 28, 2015 at 1:13
Add a ment  | 

1 Answer 1

Reset to default 5

Since you can't select elements based on their CSS state, one option would be to add a class to the element:

Updated Example

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

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

But since you said you can't do that, you could alternatively attach an event listener for the mousedown/mouseup events and change the background color accordingly:

Updated Example

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

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

..but if you want the example to work if you mouseup outside of the button element, you would need to listen to all mouseup events:

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);
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745437013a4627653.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信