Javascript 如何添加动态css类,并将活动属性附加到按钮

Javascript 如何添加动态css类,并将活动属性附加到按钮,javascript,html,jquery-ui,jquery-mobile,anchor,Javascript,Html,Jquery Ui,Jquery Mobile,Anchor,如何将以下css类动态添加到按钮 .custom-button:active{ background-image: url('images/pressed.jpg') !important; } 我使用以下代码在java脚本中创建了许多按钮。按钮已经有一个类。没有属性的自定义按钮(活动) 可以使用addClass()将任何类添加到HTML元素中 设置要添加的CSS,如下所示: .custom-button-active{ background-image: url('image

如何将以下css类动态添加到按钮

.custom-button:active{
    background-image: url('images/pressed.jpg') !important;
}
我使用以下代码在java脚本中创建了许多按钮。按钮已经有一个类。没有属性的自定义按钮(活动)

可以使用addClass()将任何类添加到HTML元素中

设置要添加的CSS,如下所示:

.custom-button-active{
    background-image: url('images/pressed.jpg') !important;
}
请注意,我将其更改为.custom按钮活动,因此它不使用伪类(因为不需要它)。现在,当您希望将此样式应用于按钮时,只需将该类添加到按钮

button.addClass('custom-button-active');

现在,除了您已经提供的任何其他类之外,按钮还将具有该类,并将使用适当的样式。

如上所述,您不能直接使用JavaScript中的伪类。但是,您可以从Javascript代码内部更改样式表。大概是这样的:

document.styleSheets[0].insertRule('.custom-button:active { background-image: url('images/pressed.jpg') !important; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';


有关该语法的更多信息,请参见此处:

您可以尝试使用jQuerys addClass()<代码>$(“#”+id).addClass(“.custom按钮:活动”).addClass()添加代码>伪类。您应该参考我可以在javascript中使用style属性将active属性添加到类中吗?为什么需要动态定义它?为什么不把它放在样式表中呢?不能使用jQuery或javascript强制应用某个伪类。
button.addClass('custom-button-active');
document.styleSheets[0].insertRule('.custom-button:active { background-image: url('images/pressed.jpg') !important; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';
var element = document.createElement('style');
document.head.appendChild(element);
var s = element.sheet;
s.insertRule('.custom-button:active {background-image: url("images/pressed.jpg") !important;}', s.cssRules.length);