Home > Web Front-end > JS Tutorial > How to use JS to change CSS styles

How to use JS to change CSS styles

autoload
Release: 2021-04-15 14:04:03
Original
2155 people have browsed it

How to use JS to change CSS styles

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>
Copy after login

1. Inline style

<script>

        //获取p标签元素
        const p=document.querySelector("p");
       //验证是否获取成功
        console.log(p);
        p.style.color="red";
    </script>
Copy after login

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>
Copy after login

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!

Related labels:
js
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