「jQuery」.scrollでスクロール処理を行うサンプル
環境
jquery 3.6.0
Google Chrome 99.0.4844.74
書式
$(window).scrollTop()
縦スクロール量を取得します。
$(window).scrollLeft()
横スクロール量を取得します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//スクロール時に呼ばれる
$(window).scroll(function(){
//縦スクロール量を取得
var top = $(window).scrollTop();
//横スクロール量を取得
var left = $(window).scrollLeft();
alert("top:" + top + " left:" + left);
});
});
</script>
</head>
<body style="height:2000px;width:2000px;">
<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(){
//スクロール時に呼ばれる
$(window).scroll(function(){
//縦スクロール量を取得
var top = $(window).scrollTop();
//横スクロール量を取得
var left = $(window).scrollLeft();
alert("top:" + top + " left:" + left);
});
});
</script>
</head>
<body style="height:2000px;width:2000px;">
<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(){ //スクロール時に呼ばれる $(window).scroll(function(){ //縦スクロール量を取得 var top = $(window).scrollTop(); //横スクロール量を取得 var left = $(window).scrollLeft(); alert("top:" + top + " left:" + left); }); }); </script> </head> <body style="height:2000px;width:2000px;"> <input type="button" id="btnShow" value="検証"> </body> </html>
実行結果
スクロールすると、現在のスクロール量「top:2 left:6」が表示されます。