JS样式操作

64 阅读1分钟

行内样式

 特点: 设置  style.属性名   设置到元素行内  
获取  style.属性名  可以获取行内的样式  获取不到文本内部以及外部样式 

box.style.width = '400px';
box.style.backgroundColor = 'black'

# 计算样式(获取文本外部的样式)

获取元素文本外属性值: 

getComputedStyle(对象).属性名字    只能获取不能设置  

##注意: 用在 --》父盒子没有限定高度 完全由内容撑开的时候  如果你想要获取父盒子高度 就可以用这个 

js  操作样式(衣服)---》  对象.className = '样式名'
对象.className = ' ' // 清除样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>买了否冷</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 100px auto;
            cursor: pointer;
            line-height: 200px;
            text-align: center;
            left: 20px;
        }
        .cloth{
            border-radius: 50%;
            background-color: gold;
            border: 2px dashed #4c8ced;
             }
    </style>
</head>
<body>
<div class="box"></div>
<script>
    window.onload = function () {
        var box = document.querySelector('.box');
        box.onclick = function () {
            box.className = 'box cloth';

        };
        box.onmouseout = function () {
            box.className = 'box';
        }
    }
</script>
</body>
</html>

默认样式:  

点击后:

鼠标离开后:


h5 操作样式(衣服)----》  对象.classList.add('样式名')
对象.classList.remove('样式名')
对象.classList.toggle('样式名')//切换样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>买了否冷</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 100px auto;
            cursor: pointer;
            line-height: 200px;
            text-align: center;
            left: 20px;
        }
        .cloth{
            border-radius: 50%;
            background-color: gold;
            border: 2px dashed #4c8ced;
            }
    </style>
</head>
<body>
<div class="box"></div>
<script>
    window.onload = function () {
        var box = document.querySelector('.box');
        box.onclick = function () {
            box.classList.toggle('cloth') ;
        };
    }
</script>
</body>
</html>

点击后在这两种样式之间切换