更改:使用jQuery的活动伪类风格 [英] Change :active pseudo-class' style with jQuery
问题描述
我正在开发一些CSS编辑器,并希望提供在单击时更改<按钮>
的样式的功能。以下代码不会将 background-color
更改为黄色。
$('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.
$('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:
$('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:
$('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:
$('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屋!