更改:使用jQuery的活动伪类风格 [英] Change :active pseudo-class' style with jQuery

查看:70
本文介绍了更改:使用jQuery的活动伪类风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

http://jsfiddle.net/65erbrhh/

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

编辑:就我而言,我无法将特定的类指定给按钮,因为它是用户可定制的HTML。

解决方案

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



已更新示例

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

$('button')。addClass('active-style');
});





  button.active- style:active {
background-color:yellow;






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

更新示例

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

..但是如果您希望示例在 mouseup 在按钮元素的 ,您需要收听全部 mouseup 事件:



更新示例

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

$('button')。addClass('active-style');
});

$(document).on('mousedown mouseup',function(e){
var color =(e.type ==='mousedown'&& $(e。目标).hasClass('active-style'))?'yellow':'';
$('button.active-style').css('background-color',color);
});


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.net/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.

解决方案

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

这篇关于更改:使用jQuery的活动伪类风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆