忍者ブログ

からすまる日誌 JavaScript

実践2(9) 画像のスライド

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

実践2(9) 画像のスライド

5枚の写真をボタンを押すたび横スクロールさせましょう。
 
ステージ配置は前と同じ
 
--->test1.html
 
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="test3.css">
  <title>slide</title>
  <script src="../jquery-3.4.1.min.js"></script>
 </head>
 <body>
  <p>
   <button id="btn">next</button>
  </p>
  <div id="frame">
   <div id="slide"></div>
  </div>
  
  <script src="test3.js"></script>
 </body>
</html>
 
--->test3.css
 
body{
 background:#333;
}
#frame{
 height: 166px;
 width: 250px;
 background-color:#333;
 margin:auto;
 position:relative;
 border: double 5px #fff;
 /*overflow:hidden;*/
}
#slide{
 height:166px;
 width:1250px;
 position:absolute;
 top:0;
 left:0;
}

こんな感じです
  
--->test3.js
$(function(){
 console.log('foo');
 
 var picture_x = 0;//画像のx座標
 
 //5枚の写真を表示
 for(i=1; i<=5; i++){
  var elehoge = $('<img>').attr('src','img/'+i+'.jpg').css('width','250px');
  $('#slide').append(elehoge);
 }
 
 $('#btn').on('click',function(){
  picture_x -= 250; 
  //もし5枚目だったら1枚目のポジションに戻す
  if(picture_x <= -1250){
   picture_x = 0;
  }
  //画像を移動
  $('#slide').animate({'left':picture_x+'px'},300,"linear");
  console.log(picture_x);
 });
});
 

ついでに左右の移動ボタンをつけて、
移動できるようにしましょう

--->test1.html
 
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="test5.css">
  <title>slide</title>
  <script src="../jquery-3.4.1.min.js"></script>
 </head>
 <body>
  <p>  
   <button id="btn02">←</button>
   <button id="btn">→</button>
   
  </p>
  <div id="frame">
   <div id="slide"></div>
  </div>
  
  <script src="test5.js"></script>
 </body>
</html>
--->test5.css
 
body{
 background:#333;
}
#frame{
 height: 166px;
 width: 250px;
 background-color:#333;
 margin:auto;
 position:relative;
 border: double 5px #fff;
 overflow:hidden;
}
#slide{
 height:166px;
 width:1250px;
 position:absolute;
 top:0;
 left:0;
}
 
--->test5.js
 
$(function(){
 console.log('foo');
 
 var picture_x = 0;//画像のx座標
 
 //5枚の写真を表示
 for(i=1; i<=5; i++){
  var elehoge = $('<img>').attr('src','img/'+i+'.jpg').css('width','250px');
  $('#slide').append(elehoge);
 }
 
 //---------------
 //右ボタンを押して画像を左にスライド
 //---------------
 $('#btn').on('click',function(){
  picture_x -= 250; 
  //もし5枚目だったら1枚目のポジションに戻す
  if(picture_x <= -1250){
   picture_x = 0;
  }
  //画像を移動
  $('#slide').animate({'left':picture_x+'px'},300,"swing");
  console.log(picture_x);
 });
 
  //---------------
  //左ボタンを押して画像を右にスライド
  //---------------
 $('#btn02').on('click',function(){
  picture_x += 250; 
  //もし5枚目だったら1枚目のポジションに戻す
  if(picture_x > 0){
   picture_x = -1000;
  }
  //画像を移動
  $('#slide').animate({'left':picture_x+'px'},300,"swing");
  console.log(picture_x);
 });
});
 
 
 
PR

コメント

ただいまコメントを受けつけておりません。

ブログ内検索

P R