var req = new XMLHttpRequest(); req.open("GET", "./json/image_list.json"); req.onreadystatechange = function(){ if(this.readyState == 4){ var data = JSON.parse(this.response);
for(var i= 0; i<data.length;i++){ var div = document.createElement("div"); div.setAttribute("class","image"); div.onclick = function(){ this.classList.toggle("image-selected"); }
div.onmouseover = function(){ var element = this; this.timerId = setTimeout( function(){ element.classList.add("image-magnified"); },1000); }
div.onmouseout = function(){ clearTimeout(this.timerId); var element = this; element.classList.remove("image-magnified"); }
var req = new XMLHttpRequest(); // 1. Ajax를 이용하기 위한 객체를 생성 req.open("GET","./json/image_list.json"); // 2. 요청방식과 URL 설정
// 3. onreadystatechange : 서버로부터 응답시 할 행동을 작성 req.onreadystatechange = function(){ // 4. 4번 -> 모든 응답이 제대로 받았을 겅우를 의미 if(this.readyState == 4){ // 5. 응답데이터(문자열)를 javascript 객체로 변환하고 div태그를 생성하여 데이터를 대입해줍니다. // div 태그의 속성은 class = "image" 로 설정합니다. var data = JSON.parse(this.response); for(var i=0;i<data.length;i++){ var div = document.createElement("div"); div.setAttribute("class","image");
// 6. img 태그를 생성하고 각 데이터를 img태그에 넣습니다. // img 태그는 div태그의 자손으로, div태그는 dody태그의 자손으로 삽입합니다. var img = document.createElement("img"); img.src = data[i]; div.appendChild(img); document.body.appendChild(div);
//밑에서 추가 진행함 } } }
req.send(); // 요청합니다.
script 파일 작성 시작 2
생성된 div 태그에 기능을 추가합니다. 기능은 총 3가지입니다.
클릭 (onclick)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// for문 안의 div.setAttribute("class","image"); 다음 줄부터 작성
// 1. 생성된 태그에 클릭 이벤트를 넣어줍니다. // 선택 및 취소 했을 경우 스타일 달리지도록 만듭니다. // 선택시 image-selected , 미선택시 image div.setAttribute("class","image"); div.onclick = function(){ if(this.getAttribute("class").indexOf("image-selected") == -1){ this.setAttribute("class","image image-selected"); } else{ this.setAttribute("class","image"); } }
위 문의 if문과 else 문은 classList 함수를 이용하여 짧게 가능.
1 2 3 4
// for문 안의 div.setAttribute("class","image"); 다음 줄부터 작성 div.onclick = function(){ this.classList.toggle("image-selected"); }
마우스 오버 (onmouseover)
1 2 3 4 5 6 7 8 9
// 2. 생성된 태그에 마우스오버 이벤트를 넣어줍니다. // div 위에 마우스가 올라갈 경우 시간만큼 스타일이 달라지도록 만듭니다. // 사용할 css style : image-magnified div.onmouseove = function(){ var element = this; this.timerId = setTimeout( function(){ element.classList.add("image-magnified"); },1000); //1초 }
마우스 아웃 (onmouseout)
1 2 3 4 5 6 7 8
// 3. 생성된 태그에 마우스아웃 이벤트를 넣어줍니다. // div 위에 마우스가 빠져나갈 경우 적용된 스타일을 제거하고 시간을 초기화 하도록 만듭니다. // 제거할 css style : image-magnified div.onmouseout = function(){ clearTimeout(this.timerId); var element = this; element.classList.remove("image-magnified"); }
html 파일 안 태그 안에 2개의 버튼을 생성하고 click 이벤트를 연결합니다.
모두 선택 및 해제 기능
각 이미지가 1번씩 크게 보여지는 슬라이드 쇼 기능
1 2 3 4 5 6
<body> <inputtype="button"value="Select All"onclick="selectAll(this)"> <inputtype="button"value="Play Slidshow"onclick="slideShow(this)"> <!-- 사용될 함수에서 해당 button 객체의 value값을 이용하기 위해 인자로 this를 넘겨줍니다. --> <hr><!-- 한줄 띄어줍니다. --> </body>