用setAttribute()追加新属性? [英] Append new attribute with setAttribute()?

查看:435
本文介绍了用setAttribute()追加新属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div元素,想向其添加新的样式属性。
我试图这样做:

I have a div element and would like to append new style attributes to it. I have tried to do it like this:

element.setAttribute('style', 'property: value');

它可以工作,但是如果该元素已经应用了样式,它们都会被覆盖。

And it works, but if that element already had styles applied, they will all get overwritten.

让我们说我有这种情况:

Lets say I have this situation:

HTML:

<div id="styled"></div>

JavaScript:

JavaScript:

var styled = document.getElementById('styled');
styled.setAttribute('style', 'display: block');

这可行,但是如果我需要添加其他样式,可以说:

This works, but if I need to append another style lets say:

styled.setAttribute('style', 'color: red');

然后我将失去在以前的setAttribute()方法中添加的样式!

I would then lose style added in previous setAttribute() method!

如何使用JavaScript将样式附加到元素上?

How can one append styles to elements with JavaScript?

谢谢!

推荐答案

好吧,如果使用 setAttribute ,则可以通过 getAttribute 并将其合并:

Well, if using setAttribute you could just take the previous value by getAttribute and concat them:

 element.setAttribute('style', element.getAttribute('style')+'; color: red');

但是,这不是大多数HTML属性的最佳做法,通常将其反映为属性,而您可以做类似 element.className + =… 之类的事情。特别是对于内联样式,您可以使用 .style 属性,可让您设置和取消设置每个CSS属性:

However, that's not the best practise for most HTML attributes, which are usually reflected as a property and you could just do something like element.className += " …". For inline styles in particular, you'd use the .style property that allows you to set and unset every single CSS property:

element.style.display = 'block';
element.style.color = 'red';

这篇关于用setAttribute()追加新属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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