Html 给元素添加css属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17857778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:29:38  来源:igfitidea点击:

Add css attribute to element

javascripthtmlcss

提问by Daniel Gustafsson

I want to add css attributes to my element. But when i do that with the code down here i loose all attributes that had an impact on the element.

我想向我的元素添加 css 属性。但是,当我使用此处的代码执行此操作时,我会丢失对元素产生影响的所有属性。

function checkNr(id) {
    var value = document.getElementById(id).value;
    if (parseFloat(value) == NaN) {
        document.getElementById(id).setAttribute("style", "border:2px solid red; background-color: rgb(255, 125, 115);");
    }
    else {
        document.getElementById(id).setAttribute("Style", "border:default; background-color: rgb(255, 255, 255);");
    }

}

Before i use this method it have the attributes:

在我使用此方法之前,它具有以下属性:

float: left;
width: 50px;

and afterward it only got the specific attributes from the javascript method. So, i want to add attributes not replace them.

之后它只从 javascript 方法中获取特定属性。所以,我想添加属性而不是替换它们。

回答by adeneo

Setting the style attribute like that, overwrites the attribute and removes previously set styles.

像这样设置样式属性,会覆盖该属性并删除以前设置的样式。

What you really should do is set the styles directly instead by changing the style property :

您真正应该做的是通过更改 style 属性直接设置样式:

function checkNr(id) {
    var elem  = document.getElementById(id),
        value = elem.value;
    if (parseFloat(value) == NaN) {
        elem.style.border = '2px solid red'; 
        elem.style.backgroundColor = 'rgb(255, 125, 115)';
    } else {
        elem.style.border = 'none'; 
        elem.style.backgroundColor = 'rgb(255, 255, 255)';
    }
}

回答by Fatih Ertu?ral

function checkNr(id) {
    var elem = document.getElementById(id);
    var css = {};
    if (parseFloat(elem.value) == NaN) {
        css = { border: '2px solid red', backgroundColor: 'rgb(255, 125, 115)' };
    } else {
        css = { border: 'none', backgroundColor: 'rgb(255, 255, 255)' };
    }

    Object.assign(elem.style, css);
}

回答by Bastaspast

jQuery option:

jQuery 选项:

$(this).css('border', 'default');

You can also pass arrays as a parameter of the .css()function. This will not override your existing css properties.

您还可以将数组作为.css()函数的参数传递。这不会覆盖您现有的 css 属性。

In your case this would be something like:

在您的情况下,这将类似于:

document.getElementById(id).css({
   border: '2px solid red;',
   background-color: 'rgb(255, 125, 115)'
});

Note that you would have to add jQuery to your project for this to work.

请注意,您必须将 jQuery 添加到您的项目中才能使其工作。

Link to jQuery css() function

链接到 jQuery css() 函数