CSS DOM dynamic styling
CSS DOM dynamic style
Use JS to operate each attribute in CSS.
JS can only operate or modify inline styles. For example: imgObj.style.border = “1px solid red”
For class styles, assign values through className. For example: imgObj.className = “imgClass”
##style object
- Each HTML tag has a style attribute. But this style attribute is also a style object.
- So, what are the properties of this style object? The attributes of the style object correspond to the attributes in CSS one-to-one.
- Therefore, the style object is used instead of CSS.
- For example: imgObj.style.border = “1px solid red”;
##Conversion between style object attributes and CSS attributes
- If it is a word, style object attributes and CSS attributes Same.
- If there are multiple words, the first word should be all lowercase, the first letter of each subsequent word should be capitalized, and the underscore should be removed.
- divObj.style.backgroundColor = “red”;
- ## divObj.style.backgroundImage = “url(images /bg.gfi)";
- divObj.style.fontSize = "18px";
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script type="text/javascript"> //网页加载完成 window.onload = init; function init() { //获取id=img01的图片对象 var imgObj = document.getElementById("img1"); //给<img>标记添加行内样式 imgObj.style.width = "400px"; imgObj.style.border = "2px solid red"; imgObj.style.padding = "20px 30px"; imgObj.style.backgroundColor = "#f0f0f0"; } </script> </head> <body > <img id="img1" src="/upload/course/000/000/009/580af7f52278b486.jpg" /> </body> </html>