Frontend/JavaScript

스크롤배너 예제

Study 2021. 3. 20. 15:56

 

마우스가 올라갈 시 정지기능! 

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>나는 개발자다.</title>
    <script>
        var imgWidth=100;
        var imgHeight=100;
        var gap=5;
        var imgcount=3;
        var container;
        var imgArray=["a.png","b.png","c.png","d.png","e.png","f.png","g.png","h.png"];
        var bannerImg= new Array;
        var targetX=0;
        var flag=true;
        function init(){
            createFrame();
            createImg();
            targetX=(bannerImg.length-1)*(gap+imgWidth);
            setInterval("flowImg()",10)
        }
        function createFrame(){
            container=document.createElement("div")
            container.style.backgroundColor="yellow";
            container.style.width=(imgWidth*imgcount)+(gap*(imgcount+1))+"px";
            container.style.height=imgHeight+(gap*2)+"px";
            container.style.margin="auto";
            container.style.position="relative";
            container.style.overflow="hidden";
            document.body.appendChild(container);
        }
        function createImg(){
            for(var i=0;i<imgArray.length;i++){
                var img=document.createElement("img")
                img.src="../images/toy/"+imgArray[i]
                img.style.width=imgWidth+"px";
                img.style.height=imgHeight+"px";
                img.style.position="absolute";
                img.style.left=(gap*(i+1))+(imgWidth*i)+"px";
                img.style.top=gap+"px";
                //이미지에 마우스 이벤트 연결
                img.addEventListener("mouseover",function(){
                    flag=false;
                });
                img.addEventListener("mouseout",function(){
                    flag=true;
                });
                //이미지부착
                container.appendChild(img);
                bannerImg[i]=img;
            }
        }
        function flowImg(){
            if(flag){
                for(var i=0;i<bannerImg.length;i++){
                    bannerImg[i].style.left=parseInt(bannerImg[i].style.left)-1+"px";
                    if(parseInt(bannerImg[i].style.left)<=-(imgWidth+gap)){
                        bannerImg[i].style.left=targetX+"px";
                    }
                }
            }
        }
        window.addEventListener("load"function(){
            init()
        });
    </script>
</head>
<body>
</body>
</html>
cs