구조분해할당,swipe
중제목 1
// 구조분해 할당 (디스트러처링)
//ES5 문법에서
//배열의 값을 호출해서 변수엠다거나 사용할때
let one;
let two;
let arr =[1,2,3,4,5];
one=arr[1];
two = arr[3];
//하나씩 인덱스를 사용해서 값을 하나씩 할당했고
console.log(one,two);
//ES6에서 도입
//구조분해 할당
//변수를 선언하고 배열 arr2의 값을 구조분해 할당해서
//순서대로 할당시킨다.
let arr2=[1,2,3,];
let [one1,two1,three1,one2]= arr2;
console.log(one1,two1,three1,one2);
//할당할 값이 없다면 언디파인이 뜬다
// 값이 순서대로 할당된다.
// let [a,b]=[1,2];
// console.log(a,b);
// //할당 되는 값이 없으면 undifined
// let [c,d]=[1];
// console.log(c,d); // 1 undifined
// // 넘쳐도 된다.
// // 순서대로 할당되는것만 보자
// let [e,f] = [1,2,3,];
// console.log(e,f); // 1 2
//변수에 디폴트 값도 추가할수있다.
let [a,b,c=3]= [1,2];
console.log(a,b,c);
//ES6에서 구조분해할당이 도입되었는데
//배열이나 객체의 값을 분해해서 편하게 변수에 할당해서 사용할수있다.
// 코드를 작성하면서 시간도 절약할수있다.
// 길이도 줄어든다.
// 객체의 구조분해 할당.
//ES5
// 객체의 값을 변수에 할당.
let name1 = {firstName: "jeong",lastName:"wook"};
// let name2=name1.firstName;
// let name3=name1.lastName;
// console.log(name2,name3);
//ES6 객체의 각 키를 뽑아서 변수에할당.
// 이친구(객체구조분해할당)는 순서가 아니다.
// 키를 기준으로 구조 분해 할당이 이루어진다.
// 순서가 아니고.
// let {lastName,firstName} = name1;
// console.log(firstName,lastName);
//객체의 디폴트값 추가
let name4= {firstName = "lee",lastName}={ lastName:"kim",firstName:"lee2"};
console.log(firstName,lastName);
// 구조분해할당
// 문자열담은 변수에서
let str= "sdasdqw";
//str.length 문자열 길이
// 구조분해 할당으로 변수에 할당
let {length}=str;
console.log(length);
// 작업할때 객체화 시켜서 작업을하다가
// 객체안에 필요한 값만 호출해서 구조분해 할당해서
// 사용할수있다.
let list =[{id:0,content:"asdasdasd",isactive:true},{id:1,content:"asdasdasd",isactive:true},{id:2,content:"asdasdasd",isactive:true}
,{id:3,content:"asdasdasd",isactive:true}];
list.forEach(function(i){
let {id,content} =i;
console.log(id,content);
})
let {id}= list;
let user={
name:"dd",
address:{
city:"seoul"
}
}
// 구조분해할당으로 city 값을 할당해보자.
let {address:{city}}=user;
console.log(city)
// 스프레드 연산자.
//스프레드 연산자 많이 사용한다.
// 스프레드 연산자 구문 ... 이렇게 작성하면된다.
// 스트레드 연산자는 본 객체를 변경하지않고
// 새로운 객체를 만들어준다/.
let temp=[1,2,3];
let temp2=[4,5,6,7];
let temp3=[...temp,...temp2];
console.log(temp3);
// 값만 참조한다. 주소 x
// 새로운객체를 만들어낸다.
let obj = {
a:1,
b:2,
}
let obj2={
a:2,
b:3,
c:1
}
let obj4={
a:3,
b:4,
c:4
}
// 키값이 동일할경우 마지막 값으로 할당된다.
let obj3={...obj,...obj2,...obj4};
console.log(obj3);
swipe
- 4
- 1
- 2
- 3
- 4
- 1
//클릭의 시작위치를 가지고있고
//끝나면 끝난 좌표와 비교를 해서
// 오른쪽으로 스와이프 된건지
// 왼쪽으로 스와이프 된건지 부터 확인을하고 인덱스를 기준으로
//움직임을 제어해보자
//마우스 시작 클릭 지점 x 좌표
let _start;
// 진행중인 인덱스
let _index = 1;
let _swiper = document.querySelector(".swiper");
let _swiperContent = document.querySelector(".swiper-content");
let { length } = document.querySelectorAll(".swiper-item");
let _prev = document.querySelector(".prev");
let _next = document.querySelector(".next");
let asd=document.querySelector('.swiper-content')
console.log(length);
//getComputedStyle 적용된 스타일의 값을 가져올수있다.
// 적용된 스타일을 가져올대그를 매개변수로 전달
let _swiperWidth = parseInt(getComputedStyle(_swiper).width);
//마우스가 눌리면
_swiper.addEventListener("mousedown", function (e) {
console.log("클릭 시작");
// 클릭했을때 x좌표
console.log(e);
_start = e.clientX;
console.log(_start);
});
_swiper.addEventListener("mouseup", function (e) {
let _start2 = e.clientX;
console.log("클릭 끝");
if((_start-_start2)>150 || (_start-_start2)<-150){
if (e.clientX < _start) {
console.log("끝 좌표가 더 작아");
if (_index < length - 1) _index++;
swiperMove();
} else {
console.log("끝좌표가 더 커");
if (_index > 0) _index--;
swiperMove();
}
}
});
//인덱스를 기준으로 움직임
function swiperMove() {
console.log("뒤짐?");
_swiperContent.style.left = -(_index * _swiperWidth) + "px";
}
_prev.addEventListener("click", function () {
if (_index > 0) _index--;
swiperMove();
console.log("뒤로");
console.log(_index);
if(_index ===0)
{
_index=4;
if(asd.classList.contains("is-active")){
}else{
asd.classList.add("is-active");
}
_swiperContent.style.left=-(_index * _swiperWidth) + "px";
}else{
asd.classList.remove("is-active");
}
});
// _next.addEventListener("click", function () {
// if (_index < length - 1) _index++;
// console.log("앞으로");
// console.log(_index);
// swiperMove();
// if(_index ===5)
// {
// _index=1;
// if(asd.classList.contains("is-active")){
// }else{
// asd.classList.add("is-active");
// }
// _swiperContent.style.left=(0)+"px";
// asd.classList.remove("is-active");
// _swiperContent.style.left=-(_index * _swiperWidth) + "px";
// // }else{
// // asd.classList.remove("is-active");
// // }
// }
// });
//0->-500 가는 만들어주기
_next.addEventListener("click", function () {
if (_index < length - 1) _index++;
console.log("앞으로");
console.log(_index);
swiperMove();
if(_index ===5)
{
_index=1;
if(asd.classList.contains("is-active")){
}else{
asd.classList.add("is-active");
}
// set the start and end values for the animation
let start = 0;
let end = -(_index * _swiperWidth);
let current = start;
// set the duration and interval for the animation
let duration = 1000; // 1 second
let interval = 10; // 10 milliseconds
// calculate the increment value for each interval
let increment = (end - start) / (duration / interval);
// create the animation loop
let animation = setInterval(function() {
current += increment;
_swiperContent.style.left = current + "px";
if (current <= end) {
clearInterval(animation);
asd.classList.remove("is-active");
_swiperContent.style.left = end + "px";
}
}, interval);
}
}
);
//412341 5에서 1갈때 모션삭제해서 1번간다음 앞의 1뒤에 다음페이지 만들고 다시 isactive 때고 강제로 이동하는 이벤트 발생 그뒤에 다음페이지를 삭제한다.
이해
if(_index ===5) { _index=1; if(asd.classList.contains("is-active")){
}else{
asd.classList.add("is-active");
}
let start = 0;
let end = -(_index * _swiperWidth); index가 1이되었을때 0 에서-500까지 애니메이션 이동을 한다. 여기서 0은 start이다
페이지가 -값이 될수록 왼쪽으로 이동하기에 - index가 된것이고 swipeWidth가 한 블럭이기때문에 이렇게 값을주게 된다.
let current = start; current 는 인덱스가 4에서 다시 1로 넘어갈때 시작하게될 애니메이션의 시작 좌표이다.
let duration = 1000; // 1 second 최종 반복시간1초
let interval = 10; // interval 1ms
let increment = (end - start) / (duration / interval);
500-0 / (1000/10)
//애니메이션 루프를 만든다 let animation = setInterval(function() { current += increment; //시작좌표에서 진행에따라서 current에 값을 더해준다. end와 start의 값이 변하지않기때문에 500-0 / (1000/10) 값이 current 값에 인터벌안에서 계속 current=current+increment 해준다. current≤ end 목표지점에 닿을때까지 _swiperContent.style.left = current + "px"; if (current <= end) { //0 ~ -500<=-500 clearInterval(animation);
닿으면 clearinterval로 끝내준다. //setinterval로 애니메이션처럼 보이게 만든것이지 트랜지션이 아님 ㄷㄷ 그다음 다시 트랜지션을 켜서 중간인덱스 값들은 평범하게 움직이게해준다. asd.classList.remove("is-active"); _swiperContent.style.left = end + "px"; } }, interval); } } );
정리하자면 트랜지션은 값이 먼저 바뀌고 바뀐값을 정해진 초동안 보여준것이라면
setIterval은 트랜지션의 시간과같이 interval 반복주기를 준뒤 꾸준히 style값을 변경해준다. 목표 숫자까지 마치 트랜지션인것처럼 처음에 목표값이 들어오냐 시작 지점에서 목표값까지 꾸준히 증가하느냐 차이
'언어 > js' 카테고리의 다른 글
| 20230329 콜백 자율공부 (0) | 2023.07.20 |
|---|---|
| 20230328 스프레드 연산자. (0) | 2023.07.20 |
| 쿠키의 이해2 (0) | 2023.07.20 |
| 20230323 나머지 매개변수 IIFE즉시실행함수 (0) | 2023.07.20 |
| 20230316 메서드 this callback (0) | 2023.07.20 |