「jQuery」offsetで要素のtop、leftを設定する

2022年2月21日

環境
jquery 3.6.0

書式
$(セレクタ名).offset({top:値1, left:値2})
offsetメソッドに指定してtop、leftのオブジェクトを生成します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
// 要素(id="btnShow")のtopを150、leftを250に設定する
$('#btnShow').click(function(){
$('#btnShow').offset({top:150, left:250});
});
});
</script>
</head>
<body>
<input type="button" id="btnShow" value="検証">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ // 要素(id="btnShow")のtopを150、leftを250に設定する $('#btnShow').click(function(){ $('#btnShow').offset({top:150, left:250}); }); }); </script> </head> <body> <input type="button" id="btnShow" value="検証"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
// 要素(id="btnShow")のtopを150、leftを250に設定する
  $('#btnShow').click(function(){
    $('#btnShow').offset({top:150, left:250});
  });
});
</script>
</head>
<body>
  <input type="button" id="btnShow" value="検証">
</body>
</html>

結果
「検証」ボタンを押すと、要素(id="btnShow")のtopを100、leftを250に設定します。

jQuery

Posted by arkgame