【合集】JavaScript 和 Jquery 设置元素的样式

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: red;
            transition: all 1s linear;
        }
        .box2{
            width: 200px;
            height: 200px;
            background-color: deepskyblue;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>
<script src="../网站后台/js/jquery-3.4.1.js"></script>
<script>
    const box = document.querySelector('.box');

    // 通过添加类名更改样式
    box.onclick = function () {
        box.className += 'box2';
    };

	const img = document.createElement('img');
	img.style = "position: absolute; top: -9999px; max-width: 100px; max-height: 100px;"

    box.onclick = function () {
        box.style.width = '200px';
        box.style.height = '200px';
        box.style.backgroundColor= 'green'; // CSS中通过-连接的样式名,在JS中变成驼峰命名 background-color => backgroundColor
    };

    box.onclick = function () {
        box.style['width'] = '200px';
        box.style['height'] = '200px';
        box.style['background-color']= 'orange'; // 这样写与CSS中的命名一致,不用驼峰命名
    };

    // 可以一次设置多条样式
    box.onclick = function () {
        box.style.cssText = `
        width: 200px;
        height: 200px;
        background-color: yellow`
    };

    box.onclick = function () {
        /**
         * @desc 语法:object.setProperty(propertyname, value, priority)
         * @param {string} propertyname  - 必需。一个字符串,表示创建或修改的属性
         * @param {string} [value]       - 可选。新的属性值
         * @param {string} [priority]    - 可选。字符串,规定是否需要设置属性的优先级 important。
         * */
        box.style.setProperty("width", "200px");
        box.style.setProperty("height", "200px");
        box.style.setProperty("background-color", "pink", "important");
    };


    /*========= 上面↑是javascript的方法,下面↓是jquery中的方法  ===========*/

    const $box = $('.box');

    $box.click(function () {
        $box.css('width', '200px');
        $box.css('height', '200px');
        $box.css('background-color', 'purple');

        $box.css('width', '200px').css('height', '200px').css('background-color', 'grey');

        $box.css({
            width: '200px',
            height: '200px',
            backgroundColor: 'blue' // 驼峰命名
        });

        $box.attr('style', `width: 200px; height: 200px; background-color: yellow`)
    })
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值