This article mainly describes how to use JavaScript
to change the inline styles and class styles in the CSS
style to simplify the daily operation process. Make the HTML
interface more concise.
Content in html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>css操作</title> <style> .bgn-cyan{ background-color: cyan; } .bgn-yellow{ background-color: #ff0; } .border{ border:3px solid #000; } .bolder{ font-weight: bolder; } p{ height: 25px; } </style> </head> <body> </body> </html>
1. Inline style
<script> //获取p标签元素 const p=document.querySelector("p"); //验证是否获取成功 console.log(p); p.style.color="red"; </script>
2. Class style
<script> const p=document.querySelector("p"); //添加类样式 p.classList.add("bgn-cyan"); //添加多个类样式 p.classList.add("border","bolder"); //对于样式的移除 p.classList.remove("bolder","border"); //对样式的替换 p.classList.replace("bgn-cyan","bgn-yellow"); //对是否有这个样式进行取反 p.classList.toggle("bgn-cyan"); //原有样式("bgn-cyan")被替换过后replace("bgn-cyan","bgn-yellow") 使用toggle("bgn-cyan")无法实现 </script>
Recommended: "2021 js interview questions and answers (large summary)"
The above is the detailed content of How to use JS to change CSS styles. For more information, please follow other related articles on the PHP Chinese website!