js 设置一个元素的高度,只能用style吗?

html-css012

js 设置一个元素的高度,只能用style吗?,第1张

JS设置一个元素的高度直接在CSS中定义其height高度是最直接高效的,也是最通用的做法。

如果在页面使用时,需要动态改变元素的高度,可以使用JS代码来重新改变这个元素的高度。比如

<div id="box" style="width:500pxheight:100pxborder:1px solid #ccc">内容</div>

<script>

//原来的div元素设置的高度是100px下面的JS可以改变其高度为300px

document.getElementById("box").style.height="300px"

</script>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>demo</title>

<style type="text/css">

    *{margin:0padding:0}

    .box{width:300pxheight:30pxbackground:#da251a}

    .click1{width:120pxheight:30pxline-height:30pxtext-align:centercolor:#fffbackground:#000margin-bottom:10px cursor:pointer}

    .click2{width:120pxheight:30pxline-height:30pxtext-align:centercolor:#fffbackground:#000cursor:pointer}

</style>

<script type="text/javascript" src="jquery-1.8.2.min.js"></script>

<script type="text/javascript">

    $(function(){

        $(".click1").click(function(){

            var bHeight=$(".box").height()

            bHeight+=30

            $(".box").css("height",bHeight)

        })

        $(".click2").click(function(){

            var bHeight=$(".box").height()

            bHeight-=30

            $(".box").css("height",bHeight)

        })

    })

</script>

</head>

<body>

<div class="click1">增加</div>

<div class="click2">减少</div>

<div class="box"></div>

</body>

</html>

自己把对应的jq库文件引入下即可。

写的不好,请谅解!