您的位置:首页 > Web前端 > JQuery

jQuery学习-宽度、高度、坐标操作

2020-08-14 23:46 876 查看

jQuery设置宽度和高度

宽度操作

$(selector).width();获取
$(selector).width(200);设置

高度操作

$(selector).height();//获取
$(selector).height(200);//设置

此方式的获取和.css获取有什么不同
$(selector).height();//返回200,number类型
$(selector).css(“height”)//返回string类型 200px

jQuery坐标操作

offset()方法

$(selector).offset()
$(selector).offset({left:100,top:150})
  • 无参数:表示获取,返回值为{left:num,top:num}.是相对于document的位置
  • 有参数:表示设置,参数建议使用number类型
    【注】设置offset后,如果元素没有定位(默认值:static),则被修改为relative

例子:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-3.4.1.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
#d1{
width: 400px;
height: 400px;
background: aquamarine;
margin: 50px;
padding: 50px;
border: 30px;
}
</style>
</head>
<body>
<div id="d1">

</div>
<script type="text/javascript">
//获取位置
console.log($("#d1").offset())
//结果{top: 50, left: 57.994789123535156},因为上面的margin和body的margin重叠了所以是50
//设置位置,计算使其达到这个位置
$("#d1").offset({
left:500,
top:500
})
</script>
</body>
</html>

position()方法

$(selector).position()

作用:获取相对于最近的带有定位的父元素的位置,返回值为对象:{left:num,top:num},只能获取,不能设置

scrollTop和scrollLeft

scrollTop和被卷去的头部距离有关

$(selector).scrollTop()//获取偏移
$(selector).scrollTop(100)//设置偏移

scrollLeft和水平滚动的距离有关

$(selector).scrollLeft()//获取偏移
$(selector).scrollLeft(100)//设置偏移

滚动的例子:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-3.4.1.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
$("#btn1").click(function(){
$('html').scrollTop(1000)
console.log($('html').scrollTop())
})
$("#btn2").click(function(){

$('html').animate({
scrollTop:0
},1000)

})
})
</script>
<button type="button" id="btn1">滚动到中间</button>
<h1>内容1</h1>
<h1>内容2</h1>
<h1>内容3</h1>
<h1>内容4</h1>
<h1>内容5</h1>
<h1>内容6</h1>
<h1>内容7</h1>
<h1>内容8</h1>
<h1>内容9</h1>
<h1>内容10</h1>
<h1>内容11</h1>
<h1>内容12</h1>
<h1>内容13</h1>
<h1>内容14</h1>
<h1>内容15</h1>
<h1>内容16</h1>
<h1>内容17</h1>
<h1>内容18</h1>
<h1>内容19</h1>
<h1>内容20</h1>
<h1>内容21</h1>
<h1>内容22</h1>
<h1>内容23</h1>
<h1>内容24</h1>
<h1>内容25</h1>
<h1>内容26</h1>
<h1>内容27</h1>
<h1>内容28</h1>
<h1>内容29</h1>
<h1>内容30</h1>
<h1>内容31</h1>
<h1>内容32</h1>
<h1>内容33</h1>
<h1>内容34</h1>
<h1>内容35</h1>
<h1>内容36</h1>
<h1>内容37</h1>
<h1>内容38</h1>
<h1>内容39</h1>
<h1>内容40</h1>
<h1>内容41</h1>
<h1>内容42</h1>
<h1>内容43</h1>
<h1>内容44</h1>
<h1>内容45</h1>
<h1>内容46</h1>
<h1>内容47</h1>
<h1>内容48</h1>
<h1>内容49</h1>
<h1>内容50</h1>
<button type="button" id="btn2">回到顶部</button>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: