jQuery设置获取样式css()

<!--@description-->
<!--@author beyondx-->
<!--@date Created in 2022/08/01/ 6:58-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #div1 {
            height: 200px;
            background-color: pink;
            border: 2px solid red;
        }
    </style>
</head>
<body>
    <input type="button" value="获取" id="getBtn"/>
    <input type="button" value="设置" id="setBtn"/>
    <div id="div1" style="width:200px">div1</div>
    <div id="div2" style="width:300px">div2</div>
    <div id="div3" style="width:400px">div3</div>

    <script src="jquery-1.12.4.js"></script>
    <script>
    // 入口函数
    $(function () {
        // css方法: 设置/获取样式

        // 1.获取样式
        $('#getBtn').click(function () {
            // 1.1.获取id为 div1这个元素的 样式
            // console.log($('#div1').css('width'));;
            // console.log($('#div1').css('height'));;
            // console.log($('#div1').css('background-color'));;
            // console.log($('#div1').css('backgroundColor'));;
            // console.log($('#div1').css('border'));;
            // 在ie中, 要获取边框这样的样式值, 记得给一个 准确的 边框

            // 1.2 获取样式, 只能获取到 第1个
            // console.log($('div').css('width')); // 200px
        });

        /**
         * 2.设置样式: css(样式名, 样式值)
         * 设置的样式 是 行内样式
         */
        $('#setBtn').click(function () {
            // 2.1. 给 id为 div1的 这个元素 设置样式
            // 设置单样式
            // $('#div1').css('width', '300px');
            // $('#div1').css('height', 300);
            // $('#div1').css('backgroundColor', 'red');
            // $('#div1').css('border', '10px solid green');

            // 设置多样式, 给个对象
            // 对象中, 可以放 key-value
            // $('#div1').css({
            //     width: 300,
            //     'height': '300px',
            //     'background-color': 'green',
            //     // backgroundColor: gray,
            //     // 'border': '10px solid gray'
            //     'border-top-width': '10px'
            // });


            // 2.2给标签为div的 元素们 设置样式
            // 这里面, 也有 隐式遍历/隐式迭代;
            // 把 每个 div都社会中为同样的样式
            $('div').css({
                'width': '50px',
                'height': '50px',
                'background-color': 'green',
                'border': '10px solid black',
                'marginTop' : '10px'
            });
        });



    });
    </script>
</body>
</html>

在这里插入图片描述

posted on 2022-08-01 07:44  beyondx  阅读(116)  评论(0编辑  收藏  举报

导航