jQuery-学习二-CSS和盒子模型

在javascript中能够为元素添加上css样式,在jquery也是行的,它主要用了.css() , addClass()。
css()是在jquery上写上属性,而.addClass()是添加外部的CSS文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQCSS</title>
    <script src="jquery-3.2.1.min.js"></script>
    <script src="test.js"></script>
    <link type="text/css" rel="stylesheet" href="test.css">
</head>
<body>
    <div></div>
</body>
</html>
$(document).ready(function () {
    $("div").css({
        width: "100px", height: "100px", backgroundColor: "#ff0000"
    });

})

通过js的代码你就能为元素添加属性了下面用一下外部引用文件。
css文件

.style1{
    width: 100px;
    height: 100px;
    background-color: blue;
}
.style2{
    width: 100px;
    height: 100px;
    background-color: green;

}

js

$(document).ready(function () {
    $("div").addClass("style1");
    $("div").click(function () {
        $("div").toggleClass("style2");
    })
})

从上面看到除了addClass方法,我还用了toggleClass方法,这是类似一个样式切换器,在二种样式之间不断的切换。

下面简单说一下盒子模型。首先说一下什么是盒子模型,在网页中一个元素占有的空间的大小是有几个部分组成的,它们分别是元素的外边距,元素的边框,元素的内边距,元素内容。而它们也构成了一个盒子模型。
而jquery中能够用它提供的方法来获取到盒子的大小,而它的方法主要是height() , innerHeight() , outHeight() , outHeight(参数)。

下面用代码来解释:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQCSS</title>
    <script src="jquery-3.2.1.min.js"></script>
    <script src="test.js"></script>
    <style>
        #div{
            width: 100px;
            height: 100px;
            padding: 50px;
            margin: 50px;
            background-color: green;
            border: 1px solid blue;
        }
    </style>
<body>
    <div id="div"></div>
    <button id="btn1">content</button>
    <button id="btn2">content+padding</button>
    <button id="btn3">content+padding+border</button>
    <button id="btn4">content+padding+border+margin</button>
</body>
</html>

js代码

$(document).ready(function () {
    $("#btn1").click(function () {
        alert($("#div").height());   //内容的高度
    });

    $("#btn2").click(function () {
        alert($("#div").innerHeight());     //内容加内边距的高度
    });

    $("#btn3").click(function () {
       alert($("#div").outerHeight());    //内容加内边距加边框的高度
    });

    $("#btn4").click(function () {
        alert($("#div").outerHeight(true));   //整个盒子的高度
    })
})

上面除了能获取高度外,其它也是能够获取到的,如宽度啊,什么的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值