2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryでの座標とサイズの取得

Posted at

jQueryでの座標とサイズの取得

時々使いたくなる座標操作やサイズの取得。
自分は忘れっぽいので使いたいときに忘れてしまい、何度も調べる事に...
なのでサンプルとしてまとめてみました。

/css/sample.css
body {
  height: 2000px;
}
div#console {
  position: fixed;
  width: 20em;
  top: 0px;
  left: 0px;
  background-color: #000000;
  color: #ffffff;
}
/js/sample.js
$(function() {
  $('body').append('<div id="console"><ul></ul></div>');
  $('div:#console ul').append('<li id="scroll"></li>')
                      .append('<li id="mouse"></li>')
                      .append('<li id="window"></li>');
  /* スクロール */
  $(window).scroll(function() {
    var x = $(this).scrollLeft();
    var y = $(this).scrollTop();
    $('li#scroll').html('scroll ' + x + ',' + y);
  /* マウス移動(画面上の位置) */
  }).mousemove(function(e){
    var x = e.clientX;
    var y = e.clientY;
    $('li#mouse').html('mouse ' + x + ',' + y);
  /* ウィンドウリサイズ(出力は描画範囲) */
  }).resize(function(){
    var w = $(this).width();
    var h = $(this).height();
    var sw = window.innerWidth - w; /* スクロールバー */
    $('li#window').html('window (' + w + '+' + sw + ')x(' + h + ')');
  /* クリックした位置が画面中央になるようスクロール */
  }).click(function(e){
    var x = e.pageX - ($(this).width() / 2);
    var y = e.pageY - ($(this).height() / 2);
    $('html,body').animate({scrollLeft: x, scrollTop: y});
  });
});
sample.html
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="./css/sample.css" />
    <script type="text/javascript" src="./js/jquery.js"></script>
    <script type="text/javascript" src="./js/sample.js"></script>
  </head>
  <body>
  </body>
</html>

注意点

$(window).height()

環境によって何が取得できるのかが違う
Windows PC + (gc ff ie):枠を含まない範囲のサイズ
iPhone + safari:メニューバーを含めた範囲のサイズ

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?