简体   繁体   English

如何添加具有激活属性的动态CSS类附加到按钮

[英]How to add dynamic css class with active property attached to button

How to add following css class dynamically to a button. 如何将以下CSS类动态添加到按钮。

.custom-button:active{
    background-image: url('images/pressed.jpg') !important;
}

i created a lot of buttons in java-script using the following code. 我使用以下代码在Java脚本中创建了很多按钮。 The buttons already have a class .custom-button button without the property (active). 这些按钮已经具有一个类.custom-button按钮,没有属性(活动)。

var ItemsToAdd = '';
ItemsToAdd += '<a id="' + id + '" data-role="button" style="background-image:url('+ img_path_normal +');border-width:0px;" class="custom-button" ></a>';                
$("#container2").append(ItemsToAdd);

the class that i already added using java script is following: 我已经使用Java脚本添加的类如下:

.custom-button {
    height: 150px !important; 
    width: 120px;
    background-size:100% 100%;
    border:0px;
    border-radius:0px;
    border-style:none;
    padding:0px;
    margin:0px;
    border-width:0px;
}

You can use addClass() to add any class to an HTML element. 您可以使用addClass()将任何类添加到HTML元素。

Set up the CSS you want to add like so: 设置您要添加的CSS,如下所示:

.custom-button-active{
    background-image: url('images/pressed.jpg') !important;
}

Notice I changed it to .custom-button-active, so it doesn't use a pseudo class (since there is no need for it). 注意,我将其更改为.custom-button-active,因此它不使用伪类(因为不需要它)。 Now, when you want this style to apply to a button simply add that class to the button. 现在,当您希望将此样式应用于按钮时,只需将该类添加到按钮。

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

Now, the button will have that class in addition to any other classes you already gave it, and will use the appropriate styles. 现在,除了您已经给它提供的任何其他类之外,按钮还将具有该类,并且将使用适当的样式。

As it was stated above, you can't directly work with pseudo-classes in JavaScript. 如上所述,您不能直接在JavaScript中使用伪类。 However, you can just change your stylesheet from inside Javascript code. 但是,您可以只从Javascript代码内部更改样式表。 Something like this: 像这样:

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

or 要么

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

More information about that syntax here: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet.insertRule 有关此语法的更多信息,请参见: https : //developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet.insertRule

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM