test5.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>
        <div id="frame">
            <div id="slide"></div>
            
            <button id="btn1">←</button>
            <button id="btn2">→</button>
        </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;
}

#btn1,#btn2{
    position:absolute;
    height:166px;
    background-color: rgba(50,50,50,0.5);
    /*opacity:0.5; でもよい*/
    cursor: pointer;
    line-height:10;
    top:0;
    color:#fff;
}
#btn1{
    left:0px;
}
#btn2{
    right:0px;
}

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);
    }
    
    //---------------
        //左ボタンを押して画像を右にスライド
        //---------------
    $('#btn1').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);
    });
    
    //---------------
    //右ボタンを押して画像を左にスライド
    //---------------
    $('#btn2').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);
    });
});

back