overflow:auto;を設定した要素内に配置している要素の位置を取得する際に少し詰まったので、取得方法などをメモしておきます。
サンプルコード
.scrollにoverflow-y: scroll;を設定して、#sample01と#sample02の位置を取得してみます。
HTML
1 2 3 4 5 6 | < div class = "scroll" > < div class = "scroll_inner" > < div id = "sample01" >sample01</ div > < div id = "sample02" >sample02</ div > </ div > </ div > |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | . scroll { width : 500px ; height : 300px ; overflow-y : scroll ; margin : 100px ; } .scroll_inner { position : relative ; height : 1000px ; } #sample 01 { position : absolute ; top : 0 ; left : 0 ; width : 100px ; height : 100px ; background : #E74C3C ; } #sample 02 { position : absolute ; top : 250px ; left : 150px ; width : 100px ; height : 100px ; background : #3498DB ; } |
offset()を使って座標を取得してみます。
JavaScript
1 2 3 4 5 6 7 8 | $(window).on( 'load' , function () { console.log( '#sample01:' , $( '#sample01' ).offset().top); console.log( '#sample02:' , $( '#sample02' ).offset().top); }); $( '.scroll' ).on( 'scroll' , function () { console.log( '#sample01:' , $( '#sample01' ).offset().top); console.log( '#sample02:' , $( '#sample02' ).offset().top); }); |
ドキュメント(html)の左上を起点とした値を取得できました。
スクロールすると対象要素が上に移動するため、スクロール量だけ座標がマイナスされます。
overflow:auto;内の要素の座標取得のデモページ
スクロール要素内での座標を取得したい場合、上記サンプルからスクロール要素の座標を引くとよさそうです。
JavaScript
1 2 3 4 5 6 7 8 9 10 | $(window).on( 'load' , function () { var base = $( '.scroll' ).offset().top; console.log( '#sample01:' , $( '#sample01' ).offset().top - base); console.log( '#sample02:' , $( '#sample02' ).offset().top - base); }); $( '.scroll' ).on( 'scroll' , function () { var base = $( '.scroll' ).offset().top; console.log( '#sample01:' , $( '#sample01' ).offset().top - base); console.log( '#sample02:' , $( '#sample02' ).offset().top - base); }); |
コメントが承認されるまで時間がかかります。