버튼은 "&lang", "&rang" 기호를 사용하여 좌우 화살표 부호를 넣어 주었고 CSS를 통하여 좌우로 정렬하려 합니다.
letprev_bttn=document.getElementById('prev');
letnext_bttn=document.getElementById('next');
letimgs=document.querySelectorAll('#slides img');
letimg_num=0;
우선 각 요소의 값들을 변수에 저 정합니다.
getElementByid()를 통하여 좌우 버튼에 대한 값을 저장하고 querySelectorAll()을 통하여 #slides의 img들의 값을 배열형태로 가져왔습니다.
imgs의 배열값을 선택하기 위해 img_num를 생성했습니다.
functionshowimg(n) {
for(leti=0;i<imgs.length;i++) {
imgs[i].style.display='none';
}
imgs[n].style.display="block"
}
setInterval(prev_bttn.onclick,2000)
화면이 전환되는 동작을 수행하는 함수 showimg()를 생성하였습니다.
변수 n값을 통하여 화면에 출력할 이미지의 배열값을 지정할 수 있도록 합니다.
for문을 통하여 전체 이미지의 display값을 "none"으로 변경하여 화면에 출력되지 않도록 하고 imgs [n]에 대한 display값만 "block"으로 지정하여 화면에 보이도록 설정하였습니다.
setinterval() 함수를 통하여 prev_bttn.onclick 이벤트를 2000밀리 초마다 실행하도록 설정하여 2초마다 자동으로 이미지 전환이 이뤄지도록 하였습니다.
버튼 클릭이벤트에 대해서는
prev_bttn.onclick=function() {
img_num--;
if(img_num<0) {
img_num=2;
}
showimg(img_num);
}
next_bttn.onclick=function() {
img_num++;
if(img_num>2) {
img_num=0;
}
showimg(img_num);
}
이미지를 3개 넣어주었기 때문에 이미지 배열은 0~2까지로 onclick 이벤트 발생 시 0에서 -1 이하로, 2에서 3 이상으로 넘어가는 것을 방지해 주기 위해서 if문을 통하여 0~2 안에서만 전환되도록 해주고 버튼을 클릭할 때마다 img_num-- , img_num++ 을 해주어 배열값이 변경되도록 설정해 주었습니다.
그리고 그 변경된 값으로 다시 showimg() 함수를 호출해 주었습니다.
3. CSS
<style>
#slideshow {
overflow: hidden;
position: relative;
width: 1200px;
height: 300px;
margin: 0auto;
}
#slide {
position: absolute;
}
#slides > img {
width: 1200px;
height: 300px;
}
button {
position: absolute;
height: 300px;
top: 0;
border: none;
padding: 20px;
background-color: transparent;
color: #000;
font-weight: 800;
font-size: 24px;
opacity: 0.5;
}
#prev {
left: 0;
}
#next {
right: 0;
}
button:hover {
background-color: #222;
color: white;
opacity: 0.6;
cursor: pointer;
}
button:focus {
border: none;
}
</style>
#slideshow{
overflow:hidden;
position:relative;
width:1200px;
height:300px;
margin:0auto;
}
#slide{
position:absolute;
}
#slides>img{
width:1200px;
height:300px;
}
#slideshow 에서 이미지가 화면을 넘어갔을 때에 화면에 보이지 않게 하기 위해서 overflow속성을 hidden값을 주었고
, position을 relative으로 설정해 주었습니다.
button{
position:absolute;
height:300px;
top:0;
border:none;
padding:20px;
background-color:transparent;
color:#000;
font-weight:800;
font-size:24px;
opacity:0.5;
}
#prev{
left:0;
}
#next{
right:0;
}
button:hover{
background-color:#222;
color:white;
opacity:0.6;
cursor:pointer;
}
button:focus{
border:none;
}
버튼은 opacity속성을 통해 투명하도록 설정하였고 left, right 값을 0을 주어 좌우 끝에 붙도록 하였습니다.