JQuery获取元素尺寸、位置及页面滚动事件应用示例

2020-05-24 21:37:54易采站长站整理

本文实例讲述了JQuery获取元素尺寸、位置及页面滚动事件应用。分享给大家供大家参考,具体如下:

获取元素尺寸


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var $div=$('.box');
//盒子内容的尺寸
console.log($div.width());
console.log($div.height());
//盒子内容加上padding的尺寸
console.log($div.innerWidth());
console.log($div.innerHeight());
//盒子的真实尺寸,内容尺寸加上padding加上brder
console.log($div.outerWidth());
console.log($div.outerHeight());
//盒子的真实尺寸加上margin
console.log($div.outerWidth(true));
console.log($div.outerHeight(true));
})
</script>
<style type="text/css">
.box{
width: 300px;
height: 200px;
padding: 20px;
border: 10px solid #000;
margin: 20px;
background-color: gold;
}
</style>
</head>
<body>
<div class="box">
dd
</div>
</body>
</html>

获取元素绝对位置


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var $div=$('.box');
//获取元素绝对位置
var oPos=$div.offset();
console.log(oPos);
$div.click(function () {
// alert(oPos.left);
document.title=oPos.left+"|"+oPos.top;
})
})
</script>
<style type="text/css">
.box{
width: 200px;
height: 200px;
background-color: #f6b544;
margin: 50px auto 0;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>

主要就是

offset()
函数

加入购物车动画

设置一个按钮,一个购物车框,一个小方框(隐藏)。点击按钮之后,小方框的位置从按钮以animate动画的形式放到购物车框,购物车的数量加一:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>