Set the height of a div element using jQuery
The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement. If the user wants to change the content height of a div dynamically, it includes changing the actual height, actual height with padding, and actual height with padding and border, then the user can use any of the following methods that will dynamically set the height of the content of an element.
- Using height() method
- Using innerHeight() method
- Using outerHeight() method
Example 1: Content Height of div using height() method will change the height of the content of an element excluding the padding, border, and margin of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the height of
a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 50px;
width: 300px;
border: 2px solid black;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the height of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content height of
a div on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Height
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-height: "+
$("#div1").height();
+ "px";
$("#p1").text(demo);
var newHeight = $(".geeks1").val();
$(".box").height(newHeight);
demo = "New-height: "+
$("#div1").height();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 2: Content Height of div using innerHeight() method will change the height of the content of an element including the padding of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the height
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 50px;
width: 300px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the height of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content height
of a div on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Height
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-height(+Padding) : "
+ $("#div1").innerHeight();
+ "px";
$("#p1").text(demo);
var newHeight = $(".geeks1").val();
$(".box").innerHeight(newHeight);
demo = "New-height(+Padding) : "+
$("#div1").innerHeight();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 3: Content Height of div using outerHeight() method will change the height of the content of an element including the padding and border of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the height
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 50px;
width: 300px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the height of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content height
of a div on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Height
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-height(border+Padding) : "
+ $("#div1").outerHeight();
+ "px";
$("#p1").text(demo);
var newHeight = $(".geeks1").val();
$(".box").outerHeight(newHeight);
demo = "New-height(border+Padding) : "
+ $("#div1").outerHeight();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Set the width of a div element using jQuery
The content width of a div can dynamically set or change using width(), innerWidth(), and outerWidth() methods depending upon the user requirement. If the user wants to change the content width of a div dynamically, it includes changing the actual width, actual width with padding, and actual width with padding and border, then the user can use any of the following methods that will dynamically set the width of the content of an element.
- Using width() method
- Using innerWidth() method
- Using outerWidth() method
Example 1: Content Width of div using width() method will change the width of the content of an element excluding the padding, border, and margin of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the width
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 100px;
width: 200px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the width of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content width of a div
on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Width
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-width : "+
$("#div1").width();
+ "px";
$("#p1").text(demo);
var newWidth = $(".geeks1").val();
$(".box").width(newWidth);
demo = "New-width : "+
$("#div1").width();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 2: Content Width of div using innerWidth() method will change the width of the content of an element including the padding of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the width
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 100px;
width: 200px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the width of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content width of a div
on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Width
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-width(+Padding) : "+
$("#div1").innerWidth();
+ "px";
$("#p1").text(demo);
var newWidth = $(".geeks1").val();
$(".box").innerWidth(newWidth);
demo = "New-width(+Padding) : "+
$("#div1").innerWidth();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 3: Content Width of div using outerWidth() method will change the width of the content of an element including the padding and border of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the width
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 100px;
width: 200px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the width of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content width of a div
on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Width
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-width(border+Padding) : "+
$("#div1").outerWidth();
+ "px";
$("#p1").text(demo);
var newWidth = $(".geeks1").val();
$(".box").outerWidth(newWidth);
demo = "New-width(border+Padding) : "+
$("#div1").outerWidth();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Set the height of a div element using jQuery
The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement. If the user wants to change the content height of a div dynamically, it includes changing the actual height, actual height with padding, and actual height with padding and border, then the user can use any of the following methods that will dynamically set the height of the content of an element.
- Using height() method
- Using innerHeight() method
- Using outerHeight() method
Example 1: Content Height of div using height() method will change the height of the content of an element excluding the padding, border, and margin of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the height of
a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 50px;
width: 300px;
border: 2px solid black;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the height of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content height of
a div on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Height
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-height: "+
$("#div1").height();
+ "px";
$("#p1").text(demo);
var newHeight = $(".geeks1").val();
$(".box").height(newHeight);
demo = "New-height: "+
$("#div1").height();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 2: Content Height of div using innerHeight() method will change the height of the content of an element including the padding of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the height
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 50px;
width: 300px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the height of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content height
of a div on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Height
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-height(+Padding) : "
+ $("#div1").innerHeight();
+ "px";
$("#p1").text(demo);
var newHeight = $(".geeks1").val();
$(".box").innerHeight(newHeight);
demo = "New-height(+Padding) : "+
$("#div1").innerHeight();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 3: Content Height of div using outerHeight() method will change the height of the content of an element including the padding and border of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the height
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 50px;
width: 300px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the height of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content height
of a div on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Height
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-height(border+Padding) : "
+ $("#div1").outerHeight();
+ "px";
$("#p1").text(demo);
var newHeight = $(".geeks1").val();
$(".box").outerHeight(newHeight);
demo = "New-height(border+Padding) : "
+ $("#div1").outerHeight();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Set the width of a div element using jQuery
The content width of a div can dynamically set or change using width(), innerWidth(), and outerWidth() methods depending upon the user requirement. If the user wants to change the content width of a div dynamically, it includes changing the actual width, actual width with padding, and actual width with padding and border, then the user can use any of the following methods that will dynamically set the width of the content of an element.
- Using width() method
- Using innerWidth() method
- Using outerWidth() method
Example 1: Content Width of div using width() method will change the width of the content of an element excluding the padding, border, and margin of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the width
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 100px;
width: 200px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the width of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content width of a div
on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Width
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-width : "+
$("#div1").width();
+ "px";
$("#p1").text(demo);
var newWidth = $(".geeks1").val();
$(".box").width(newWidth);
demo = "New-width : "+
$("#div1").width();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 2: Content Width of div using innerWidth() method will change the width of the content of an element including the padding of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the width
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 100px;
width: 200px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the width of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content width of a div
on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Width
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-width(+Padding) : "+
$("#div1").innerWidth();
+ "px";
$("#p1").text(demo);
var newWidth = $(".geeks1").val();
$(".box").innerWidth(newWidth);
demo = "New-width(+Padding) : "+
$("#div1").innerWidth();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
Example 3: Content Width of div using outerWidth() method will change the width of the content of an element including the padding and border of the element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
How to dynamically set the width
of a div element using jQuery?
</title>
<script src=
</script>
<style>
#div1 {
height: 100px;
width: 200px;
border: 2px solid black;
padding : 10px;
}
h1 {
color: green;
}
.box{
background: green;
border: 1px solid #ccc;
color: white;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Dynamically set the width of
a div element using jQuery</h3>
<div id="div1" class="box">
Dynamically set content width of a div
on GeeksforGeek.<br>
GeeksforGeeks is
a computer science portal which
helps students to learn various
programming language and master
data structures and algorithms.
There are various courses available
to learn new skills.
</div>
<br>
<form>
<input type="text" class="geeks1">
<button type="button" class="geeks2">
Set Width
</button>
</form>
<p id="p1"></p>
<p id="p2"></p>
</center>
<script>
$(document).ready(function(){
$(".geeks2").click(function(){
var demo ="Previous-width(border+Padding) : "+
$("#div1").outerWidth();
+ "px";
$("#p1").text(demo);
var newWidth = $(".geeks1").val();
$(".box").outerWidth(newWidth);
demo = "New-width(border+Padding) : "+
$("#div1").outerWidth();
+ "px";
$("#p2").text(demo);
});
});
</script>
</body>
</html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.

Мы с Вами когда-то разбирали перемещение div на JavaScript, а сегодня мы разберём изменение размеров div на JavaScript, которое так же может быть очень удобно для пользователей сайта.
Для начала разберём HTML-код:
<div id="block">
<span>Блок</span>
<br />
<span>Текст</span>
<div id="block_resize"></div>
</div>
Думаю, тут всё более чем понятно. Что касается «block_resize«, то именно его и надо будет «тянуть» для изменения размеров блока.
Разберём CSS-код:
#block {
background-color: #ff0;
min-height: 100px;
min-width: 200px;
position: relative;
width: 400px;
}
#block_resize {
background-color: #000;
bottom: 0;
cursor: se-resize;
height: 12px;
margin-top: 9px;
position: absolute;
right: 0;
width: 12px;
}
Теперь разберём самое главное и самое сложное — код JavaScript:
<script type="text/javascript">
var ie = 0;
var op = 0;
var ff = 0;
var block; // Основной блок
var block_r; // Блок для изменения размеров
var delta_w = 0; // Изменение по ширине
var delta_h = 0; // Изменение по высоте
/* После загрузки страницы */
onload = function () {
/* Определяем браузер */
var browser = navigator.userAgent;
if (browser.indexOf("Opera") != -1) op = 1;
else {
if (browser.indexOf("MSIE") != -1) ie = 1;
else {
if (browser.indexOf("Firefox") != -1) ff = 1;
}
}
block = document.getElementById("block"); // Получаем основной блок
block_r = document.getElementById("block_resize"); // Получаем блок для изменения размеров
document.onmouseup = clearXY; // Ставим обработку на отпускание кнопки мыши
block_r.onmousedown = saveWH; // Ставим обработку на нажатие кнопки мыши
}
/* Функция для получения текущих координат курсора мыши */
function getXY(obj_event) {
if (obj_event) {
x = obj_event.pageX;
y = obj_event.pageY;
}
else {
x = window.event.clientX;
y = window.event.clientY;
if (ie) {
y -= 2;
x -= 2;
}
}
return new Array(x, y);
}
function saveWH(obj_event) {
var point = getXY(obj_event);
w_block = block.clientWidth; // Текущая ширина блока
h_block = block.clientHeight; // Текущая высота блока
delta_w = w_block - point[0]; // Измеряем текущую разницу между шириной и x-координатой мыши
delta_h = h_block - point[1]; // Измеряем текущую разницу между высотой и y-координатой мыши
/* Ставим обработку движения мыши для разных браузеров */
document.onmousemove = resizeBlock;
if (op || ff) document.addEventListener("onmousemove", resizeBlock, false);
return false; // Отключаем стандартную обработку нажатия мыши
}
/* Функция для измерения ширины окна */
function clientWidth() {
return document.documentElement.clientWidth == 0 ? document.body.clientWidth : document.documentElement.clientWidth;
}
/* Функция для измерения высоты окна */
function clientHeight() {
return document.documentElement.clientHeight == 0 ? document.body.clientHeight : document.documentElement.clientHeight;
}
/* При отпускании кнопки мыши отключаем обработку движения курсора мыши */
function clearXY() {
document.onmousemove = null;
}
function resizeBlock(obj_event) {
var point = getXY(obj_event);
new_w = delta_w + point[0]; // Изменяем новое приращение по ширине
new_h = delta_h + point[1]; // Изменяем новое приращение по высоте
block.style.width = new_w + "px"; // Устанавливаем новую ширину блока
block.style.height = new_h + "px"; // Устанавливаем новую высоту блока
/* Если блок выходит за пределы экрана, то устанавливаем максимальные значения для ширины и высоты */
if (block.offsetLeft + block.clientWidth > clientWidth()) block.style.width = (clientWidth() - block.offsetLeft) + "px";
if (block.offsetTop + block.clientHeight > clientHeight()) block.style.height = (clientHeight() - block.offsetTop) + "px";
}
</script>
Код я постарался хорошо прокомментировать, поэтому разобраться в нём можно. Если Вы читали про перемещение div с помощью JavaScript, то Вы заметили огромную схожесть, что неудивительно, ведь используется тот же механизм drag-and-drop.
В любом случае, даже если Вы затрудняетесь в понимании кода, Вы можете его копировать, заменив только имена блоков, и вставить к себе на сайт. Никаких jQuery данный код не требует, что также является большим преимуществом данного скрипта.
-
Создано 23.09.2013 08:40:32
-
Михаил Русаков
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
-
Кнопка:
Она выглядит вот так:
-
Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт
- BB-код ссылки для форумов (например, можете поставить её в подписи):
- Связанные категории:
- Dimensions
- CSS
-
Manipulation
» Style Properties
#
#
Возвращает, устанавливает высоту элемента.
-
version added: 1.0.height()
Возврат: Целое число
Получает высоту элемента.
-
version added: 1.0.height( value )
value
Тип: Строка или Число
Целое число, представляющее количество пикселей, или число с единицей измерения в виде строки. -
version added: 1.4.1.height( function(index, height) )
Тип: Функция
Устанавливает высоту элемента, значение которой возвращает функция function(index, height). Функции передается 2 аргумента — index (индекс текущего элемента) и текущая высота
Разницу между .css(‘height’) и .height() в том, что данный метод возвращает исключительно числовое значение (к примеру, 400, а не 400px). Метод .height() рекомендуется использовать, когда полученное значение необходимо задействовать в математических вычислений.
Данный метод можно использовать для получения высоты документа и окна.
$(window).height(); $(document).height();
Заметьте, что метод .height() всегда возвращает высоту контента, не учитывая значение свойства CSS box-sizing. Начиная с jQuery 1.8, вам необходимо получить значение свойства box-sizing, затем отнять размер рамки и отступов. Всё это в том случае, если к элементу применяется свойство box-sizing: border-box. Чтобы избежать этих вычислений, используйте .css(«height»).
В метод .height(value), можно передать как строку, так и число. Если передано только число, то jQuery автоматом прибавляет “px”. Если строка, то она должна выглядеть так: 100px, 50%, или auto. Просим заметить, что в современных бразуерах в высоту не входят значения отступов и рамки.
Примеры:
Пример: Показать различия значений высоты. Поскольку элементы находятся в iframe, то настоящие размеры могут быть чуть другими.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>height demo</title>
<style>
body { background:yellow; }
button { font-size:12px; margin:2px; }
p { width:150px; border:1px red solid; }
div { color:red; font-weight:bold; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<button id="getp">Get Paragraph Height</button>
<button id="getd">Get Document Height</button>
<button id="getw">Get Window Height</button>
<div> </div>
<p>
Sample paragraph to test height
</p>
<script>
function showHeight(ele, h) {
$("div").text("The height for the " + ele +
" is " + h + "px.");
}
$("#getp").click(function () {
showHeight("paragraph", $("p").height());
});
$("#getd").click(function () {
showHeight("document", $(document).height());
});
$("#getw").click(function () {
showHeight("window", $(window).height());
});
</script>
</body>
</html>
Демо:
Пример: Задать при клике по элементу div высоту 30px.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>height demo</title>
<style>div { width:50px; height:70px; float:left; margin:5px;
background:rgb(255,140,0); cursor:pointer; } </style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>$("div").one('click', function () {
$(this).height(30)
.css({cursor:"auto", backgroundColor:"green"});
});</script>
</body>
</html>
Демо:








