html代码
<p style="color:blue;">武汉PHP培训-武汉长乐教育</p>
css()方法
$("p").css("color") //获取颜色样式
$("p").css("color", "red"); //设置样式
$("p").css({"color":"red", "font-size":"20px"});
height()和width()方法
$("p").height(); //获取高度
$("p").height("100px"); //设置高度
$("p").width(); //获取宽度
$("p").width("400px") //设置宽度
offset()方法
var offset = $(".children").offset(); //获取元素在当前视窗的相对偏移
//console.log(offset)
var left = offset.left; //获取左偏移
var top = offset.top; //获取上偏移
position()方法
var position = $(".children").position(); //获取relative或absolute元素的祖先节点相对偏移
var left = position.left; //获取左偏移
var top = position.top; //获取上偏移
下面看例子
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<style type="text/css">
.parent{
width: 500px;
height: 500px;
border: 1px solid;
position: relative;
top:100px;
left:300px;
}
.children{
width: 100px;
height: 100px;
border: 1px solid #08c;
position: absolute;
top:100px;
left:300px;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
scrollTop()方法和scrollLeft()方法
<html>
<head>
<title></title>
<meta charset="utf-8">
<style type="text/css">
.parent{
width: 200px;
height: 200px;
border: 1px solid;
overflow: auto;
}
.children {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">
scrollTop()方法和scrollLeft()
</div>
</div>
<button class="button1">获取scrollTop</button><br>
<button class="button2">设置scrollTop</button>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
$(".button1").click(function(){
var scrollTop=$("div").scrollTop(); //获取元素滚动条距离上面的位置
var scrollLeft=$("div").scrollLeft(); //获取元素滚动条距离左边的位置
})
$(".button2").click(function(){
$("div").scrollTop(200); //设置元素滚动条距离上面的位置
$("div").scrollLeft(200); //设置元素滚动条距离左边的位置
})
})
</script>
</body>
</html>