jQuery touchstartイベントでスマホのタッチ開始のイベントを取得するサンプル
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
1.タッチ開始イベントを取得します
$('指定要素’).on('touchstart’, function () {処理コード}
touchstart イベントは、タッチ平面上に 1 つ以上のタッチ点が配置されたときに発生します。
2.タッチ終了イベントを取得します
$('指定要素’).on('touchend’, function () {処理コード}
touchend イベントは、タッチ面から 1 つ以上のタッチ点が取り除かれた場合に発生します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// タッチ開始イベント
$('#img').on('touchstart', function () {
$('#img').attr('src', 'logo2.png')
})
// タッチ終了イベント
$('#img').on('touchend', function () {
$('#img').attr('src', 'logo1.png')
})
});
</script>
</head>
<body>
<div>
<img id="img" src="logo1.png">
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// タッチ開始イベント
$('#img').on('touchstart', function () {
$('#img').attr('src', 'logo2.png')
})
// タッチ終了イベント
$('#img').on('touchend', function () {
$('#img').attr('src', 'logo1.png')
})
});
</script>
</head>
<body>
<div>
<img id="img" src="logo1.png">
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ // タッチ開始イベント $('#img').on('touchstart', function () { $('#img').attr('src', 'logo2.png') }) // タッチ終了イベント $('#img').on('touchend', function () { $('#img').attr('src', 'logo1.png') }) }); </script> </head> <body> <div> <img id="img" src="logo1.png"> </div> </body> </html>
実行結果
指定要素「id="img"」をタップすると、画像が変更されます。