Home > Web Front-end > JS Tutorial > body text

Add multiple styles to elements through js, fully compatible with browsers_javascript skills

WBOY
Release: 2016-05-16 16:38:24
Original
2167 people have browsed it

js adds multiple styles to elements, fully compatible with browsers. Example writing method:

<a href="javascript:;" id="test" style="font-size:25px;background:#080;">测试3</a>
<script>
var obj=document.getElementById("test");
var oldStyle=obj.style.cssText;
alert(oldStyle);
obj.style.cssText="border:2px red solid;color:#f00;"+oldStyle;
</script>
Copy after login

js adds multiple styles to elements. The quickest and most convenient way is to use the cssText attribute, but it will rewrite the original value of the entire style. To retain the original style value, it is very simple. You can do it like the example above, Use a variable to record the original style original value, and then do a string concatenation.

But one thing to note is: the last style value returned by obj.style.cssText in browsers IE8 and below does not have a semicolon, and looks like: font-size:25px;background:#080. I just want to say that ie is as unpleasant as ever, haha.

So in the example, oldStyle is intentionally placed after the string splicing. In this way, even if the last style value of the spliced ​​style string does not have a semicolon, there will be no problem. The style application display in each browser will be consistent. This is also It’s a little trick, it’s not very technical, but it’s easy to ignore or forget. I know I have a bad memory, so I’ll mark it ^_^

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!