19、卷曲距离(滚动条的位置)
2022-09-01 本文已影响0人
一直流浪
方法:
- scrollLeft()
- 获取元素内容被卷曲进去的宽度
- scrollTop()
- 获取元素内容被卷曲进去的高度
- scrollLeft(数值)
- 设置元素内容被卷曲进去的宽度
- scrollTop(数值)
- 设置元素内容被卷曲进去的高度
案例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
padding: 0;
margin: 0;
}
body{
width: 2000px;
height: 2000px;
}
div{
width: 200px;
height: 200px;
border: 1px solid red;
overflow: auto;
}
img{
vertical-align: top;
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<input type="button" value="按钮" id="btn" />
<div>
<img src="img/1.jpg"/>
</div>
</body>
</html>
<script type="text/javascript" src="js/jQuery.js" ></script>
<script>
$(function(){
$('#btn').click(function(){
//1.获取和设置元素被卷曲的距离
//(1)获取
//scrollLeft() 获取元素内容被卷曲进去的宽度
//scrollTop() 获取元素内容被卷曲进去的高度
console.log($('div').scrollLeft());
console.log($('div').scrollTop());
//(2)设置
//scrollLeft(数值) 设置元素内容被卷曲进去的宽度
//scrollTop(数值) 设置元素内容被卷曲进去的高度
$('div').scrollLeft(200);
$('div').scrollTop(100);
//2.获取和设置页面被卷曲的距离
//(1)获取
//获取页面被卷曲的宽度
console.log($(window).scrollLeft());
//获取页面被卷曲的高度
console.log($(window).scrollTop());
//(2)设置
$(window).scrollLeft(1000);
$(window).scrollTop(1000)
})
})
</script>
案例:固定导航栏
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>固定导航栏</title>
<style>
body{
width: 1080px;
height: 720px;
}
.top{
width: 1080px;
height: 100px;
background: red;
}
.nav{
width: 1080px;
height: 100px;
background: navy;
}
.main{
margin-top: 10px;
width: 1080px;
height: 5000px;
background: green;
}
</style>
</head>
<body>
<div class="top"></div>
<div class="nav"></div>
<div class="main"></div>
</body>
</html>
<script type="text/javascript" src="js/jQuery.js" ></script>
<script>
$(function(){
//给页面设置一个滚动事件
//计算头部的高度
var topHeight = $('.top').height();
//计算导航栏的高度
var navHeight = $('.nav').height();
$(window).scroll(function(){
//1.获取页面被卷曲的距离
var scrollTopValue = $(window).scrollTop();
console.log(scrollTopValue);
//2.判断
if(scrollTopValue>=topHeight){
//固定导航栏
$('.nav').css({
position:'fixed',
top:0,
left:0
});
//设置内容部分的margin-top的值为导航栏的高度
$('.main').css({
marginTop:navHeight+10
});
}else{
//让导航栏的定位还原
$('.nav').css({
position:'static',
top:0,
left:0
});
//让内容部分的margin-top的值还原
$('.main').css({
marginTop:10
});
}
})
})
</script>