jQuery获取与设置div的宽和高

    前端页面开发时,通过jquery有两种方法获取与设置div的宽高:使用尺寸函数或使用css方法。

    一、获取宽和高

    1.1 尺寸函数:

width() 获取宽度
height() 获取高度

    1.2 css方法:

css("width")获取宽度
css("height")获取高度

    区别:

        尺寸函数返回的值为整型,而css获取的值为带px的字符串

    举例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache,must-ridate">
    <meta http-equiv="expires" content="0">
    <script src="./plugins/jquery/jquery.min.js"></script>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: grey;
        }
    </style>
</head>
<body>
<div class="box">
</div>
<input type="button" οnclick="handleClick()" value="获取宽高">
<input type="button" οnclick="handleClick()" value="改变宽高">
</body>
<script>
    function handleClick() {
        // 1. 使用width(),height()方法来获取宽高,返回的是整形数字
        var divw = $('.box').width();
        var divh = $('.box').height();
        console.log("div宽:" + divw + ";div高:" + divh);

        // 2.使用css方式获取宽高,返回的带px的字符串
        var divw = $('.box').css("width");
        var divh = $('.box').css("height");
        console.log("div宽:" + divw + ";div高:" + divh);
    }
</script>
</html>

    以上两种方式,输出的值为:

div宽:200;div高:200
div宽:200px;div高:200px

    二、设置宽和高

    2.1 尺寸函数:

width(整数值)设置宽度
height(整数值)设置高度

    2.2 css方法:

css({"width":"整数值px","height":"整数值px"}) // 使用css设置多个属性时,放在大括号中属性间用逗号分隔
或
css("width","整数值px") // 使用css设置单个属性时,将属性名称与属性值使用逗号分隔(不需要放到大括号中)
css("height","整数值px")

    区别:

        尺寸函数设置的值为整型,而css设置的值为带px的字符串

    举例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache,must-ridate">
    <meta http-equiv="expires" content="0">
    <script src="./plugins/jquery/jquery.min.js"></script>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: grey;
        }
    </style>
</head>
<body>
<div class="box">
</div>
<input type="button" οnclick="handleSet1()" value="改变宽高(函数)">
<input type="button" οnclick="handleSet2()" value="改变宽高(CSS)">
</body>
<script>
    function handleSet1() {
        // 1. 使用width(),height()方法来设置宽高
        var divw = $('.box').width(100);
        var divh = $('.box').height(150);
    }

    function handleSet2() {
        // 2.使用css方式来设置宽高
        var divw = $('.box').css("width", "20px");
        var divh = $('.box').css("height", "20px");
    }
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值