Love beautiful code? We do too.
.offset(): Lấy tọa độ hiện tại của thành phần đầu tiên, hoặc thiết lập các tọa độ của từng thành phần trong tập hợp các thành phần phù hợp liên quan đến văn bản.
Đã được thêm vào từ phiên bản 1.2
.offset()
$('p').offset();
Đã được thêm vào từ phiên bản 1.4
.offset(tọa độ)
$('p').offset({ top: 10, left: 20 });
.offset(function(index,tọa độ){...})
$('p').offset(function(index,{ top: 10, left: 20 }){...});
Html viết:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
var offset = $('div').offset();
$('span').text(offset.left+" , "+offset.top);
});
</script>
</head>
<body>
<p>Tọa độ của thành phần div: (<span></span>)</p>
<div>Tag div</div>
</body>
</html>
Hiển thị trình duyệt:
Cách sử dụng $('div').offset() ta đã lấy được giá trị tọa độ của thành phần div.
Html viết:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
p { background-color: pink; }
div { background-color: yellow; }
</style>
<script>
$(function(){
$('div').offset({top: 80, left: 300 });
});
</script>
</head>
<body>
<p>Tag p</p>
<div>Tag div</div>
</body>
</html>
Hiển thị trình duyệt:
Tọa độ của thành phần div hiện giờ đã được thay đổi, tương đương đoạn sytle sau: position: relative; top: 80px; left: 300px;.
Html viết:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
p { background-color: blue; }
</style>
<script>
$(function(){
$('button').on('click', function() {
$('p').offset(function(index, coordinates){
if (index == 0) {//Chỉ tác động lên thành phần đầu tiên
coordinates.top += 10;
coordinates.left += 10;
}
return $(this).offset(coordinates);
});
});
});
</script>
</head>
<body>
<p>Tag p 01</p>
<p>Tag p 02</p>
<button>Click</button>
</body>
</html>
Hiển thị trình duyệt:
Khi click vào button, ta đã cộng thêm vào 10px của tọa độ x và y
Hoclaptrinh.vn © 2017
From Coder With
Unpublished comment
Viết câu trả lời