$(document).ready(function () {
    $("#scroll").on("click", function (event) {
        var offset = $(".Sec6").offset().top;
        // swiper.mousewheel.disable();
        $("html, body").animate({
            scrollTop: offset,
        }, 400);
        console.log(offset);
    });
});

✅ javascript
1) #scroll 이라는 id 버튼을 누르면
2) .Sec6 class 상단으로 이동한다
3) 부드럽게 이동하기 위해 animate 추가

    <div class="swiper slide">
        <div class="swiper-wrapper">
            <div class="swiper-slide">
            슬라이드내용
            </div>
         </div>
         <div class="swiper-wrapper">
            <div class="swiper-slide">
            슬라이드내용
            </div>
         </div>
         <div class="swiper-wrapper">
            <div class="swiper-slide">
            슬라이드내용
            </div>
         </div>
         <div class="swiper-wrapper">
            <div class="swiper-slide">
            슬라이드내용
            </div>
         </div>
         <div class="swiper-wrapper">
            <div class="swiper-slide">
            슬라이드내용
            </div>
         </div>
        <div class="swiper-pagination"></div>
    </div>

✅html
1) swiper slider에서 html가져오기

//Initialize Swiper
var swiper = new Swiper(".slide", {
    direction: "vertical",
    sensitivity: 3,
    mousewheel: true,
    touchRatio: 2,
    // followFinger: false,
    pagination: {
        el: ".slide .swiper-pagination",
        type: "fraction",
    },
    on: {
        reachEnd: function () {
            swiper.mousewheel.disable();
        }
    }
});
// 슬라이드 가장 마지막에서 스크롤 활성화
window.addEventListener('wheel', function (event) {
    if (event.deltaY < 0) {
        swiper.mousewheel.enable();
    } else if (event.deltaY > 0) { }
});

✅css
1) swiper slider에서 script내용가져오기
2) swiper slider API에서 필요한 부분 가져오기
- mouse wheel로 작동 될 수 있게 하였다
- 스크롤, 터치에 대해 민감하게 휙휙 넘어가는 듯한 느낌을 위해 sensitivity와 touchRatio 값을 주었다
3) pagination 숫자로 보이게 추가
4) 슬라이더가 작동할 때 마우스 휠에 움직이지 않는다는 명령어를 작성

5) 휠 이벤트를 주어 if Y가 0보다 작으면 휠이 작동하지 않고 else if Y가 0보다 크면 작동한다는 함수 작성

✔ touch시 마지막 슬라이드가 움직이지 않는 현상

javascript form 요소를 이용해서 상품 구매 페이지 만들기

<div class="form">
                    <div class="left">
                        <h3>선택내역</h3>
                        <div id="container">
                        </div>
                    </div>
                    <div class="right">
                        <div class="select">
                            <h3>
                                분류
                            </h3>
                            <div>
                                <select id="selGoods" name="selGoods"></select>
                                <button id="btnAddGoods">추가하기</button>
                            </div>
                        </div>
                        <div>
                            <h3>
                                합계
                            </h3>
                            <input id="goodsTotAmt" name="totAmt" value="0">
                        </div>
                    </div>
                </div>
                <input type="button" value="구매하기" class="button2" onClick="alert('해당페이지는 포트폴리오 페이지로 구매할 수 없습니다.')">
            </div>

✅html
1) 왼쪽에 선택목록이 나타나기 위한 빈 div만들기
2) 오른쪽에는 선택할 수 있는 select form과 추가하기 버튼 작성
3) 합계를 보여주기 위해 input으로 작성
4) 가장하단에는 구매하기 button을 작성

function Goods(){
		this.arrAllGoods = new Array();//상품 목록
		this.arrSelGoods = new Array();//선택한 상품 목록
		var p = this;
		//상품 추가 시
		this.select = function (trgtGoodsId){
			var selectedIndex = -1;
			//전체 목록 배열에서 검색하여 goodsId가 없다면 선택 목록에 push후 container안에 그려준다.
			//선택 목록에서 검색
			for(var i=0;i<p.arrSelGoods.length;i++){
				if(p.arrSelGoods[i].goodsId==trgtGoodsId){
					selectedIndex = i;
					break;
				}
			}
			if(selectedIndex<0){//선택목록에 없을 경우 추가. 잇을경우 얼럿.
				//전체목록에서 선택 추가해줌.
				for(var j=0;j<p.arrAllGoods.length;j++){
					
					if(p.arrAllGoods[j].goodsId==trgtGoodsId){
						p.arrSelGoods.push(p.arrAllGoods[j]);
						p.arrSelGoods[p.arrSelGoods.length-1].cnt = 0;//무조건 개수 초기화
						p.appendChoiceDiv(p.arrAllGoods[j]);
						break;
					}
				}
			}else{
				alert("이미 추가한 상품입니다.");
			}
			p.afterProc();
		}
		//상품 제거 시
		this.deselect = function (trgtGoodsId){
			var selectedIndex = -1;
			//배열에서 검색.
			for(var i=0;i<p.arrSelGoods.length;i++){
				if(p.arrSelGoods[i].goodsId==trgtGoodsId){
					p.removeChoiceDiv(p.arrSelGoods[i]);
					p.arrSelGoods.splice(i,1);
					break;
				}
			}
			p.afterProc();
		}
		this.appendChoiceDiv = function(prmtObj){
			var innerHtml = "";
			innerHtml += '<div id="div_'+prmtObj.goodsId+'">';			
			innerHtml += '<ul>';
			innerHtml += '	<li>'+prmtObj.goodsNm+'</li>';
			innerHtml += '	<li>수량:<input type="text" id="input_cnt_'+prmtObj.goodsId+'" name="" value="0"/>'
            innerHtml += '	<li><button type="button" id="" class="add" name="" onclick="goods.minus(\''+prmtObj.goodsId+'\');">-</button></li>';
            innerHtml += '	<li><button type="button" id="" class="remove" name="" onclick="goods.plus(\''+prmtObj.goodsId+'\');">+</button></li>';
            innerHtml += '	<li><button type="button" id="" class="remove" name="" onclick="goods.deselect(\''+prmtObj.goodsId+'\');">제거</button></li>';
			innerHtml += '	<li>가격:<input type="text" id="input_sumAmt_'+prmtObj.goodsId+'" name="" value="0"/><span> 원</span>'
			innerHtml += '</ul>';
			innerHtml += '</div>';		
			$('#container').append(innerHtml);
		}
		this.removeChoiceDiv = function(prmtObj){
			$("#div_"+prmtObj.goodsId).remove();
		}
		this.plus = function (trgtGoodsId){
			for(var i=0;i<p.arrSelGoods.length;i++){
					if(p.arrSelGoods[i].goodsId==trgtGoodsId){
						p.arrSelGoods[i].cnt++;
						break;
					}
			}
			p.afterProc();			
		}
		this.minus = function (trgtGoodsId){
			for(var i=0;i<p.arrSelGoods.length;i++){	
					if(p.arrSelGoods[i].goodsId==trgtGoodsId){
						if(p.arrSelGoods[i].cnt==0) break;
						p.arrSelGoods[i].cnt--;
						break;
					}
			}
			p.afterProc();			
		}
		//계산 후처리.
		this.afterProc = function (){
			for(var i=0;i<p.arrSelGoods.length;i++){
				$('#input_cnt_'+p.arrSelGoods[i].goodsId).val(p.arrSelGoods[i].cnt);
				$('#input_sumAmt_'+p.arrSelGoods[i].goodsId).val(p.arrSelGoods[i].cnt*p.arrSelGoods[i].goodsUnprc);
			}
			var goodsTotAmt = 0;
			for(var i=0;i<p.arrSelGoods.length;i++){
				goodsTotAmt += p.arrSelGoods[i].cnt*p.arrSelGoods[i].goodsUnprc;
			}
			$('#goodsTotAmt').val(goodsTotAmt + ' 원');
		}
	}	
	var goods = new Goods();
	//jstl로 전체 상품 목록 미리 세팅
	goods.arrAllGoods.push({goodsId:"1",goodsUnprc:20000,goodsNm:"성인"  ,cnt:0});
	goods.arrAllGoods.push({goodsId:"2",goodsUnprc:15000,goodsNm:"청소년"  ,cnt:0});
	goods.arrAllGoods.push({goodsId:"3",goodsUnprc:13000,goodsNm:"어린이",cnt:0});
	//jstl로 셀렉트 박스 옵션 채우기
    $('#selGoods').append('<option id="" value="1">성인</option>');
	$('#selGoods').append('<option id="" value="2">청소년</option>');
	$('#selGoods').append('<option id="" value="3">어린이</option>');
	$('#btnAddGoods').on('click',function(){
		goods.select($('#selGoods option:selected').val());
	});

✅css
1) 상품과 선택 상품에 대해 배열을 만든다
2) 전체 목록 배열에서 goodsId가 없으면 선택목록에 추가, 있으면 추가되지않고 alert이 띄워지는 함수작성
3) html 추가하는 함수 작성
- 선택된 목록 이름 추가
- ul li 태그로 수량, +버튼, -버튼, 목록제거버튼, 해당목록 가격 작성
4) 해당 태그 id를 불러와 +버튼, -버튼, 목록제거버튼에 대한 함수작성
5) 계산 이후 전체 합계에 대한 함수 작성
-해당 input id를 불러와 결과값을 해당 id로 추출
6) 선택 목록 세팅
- 상품명, 가격등 작성
7) 셀렉트 박스 옵션 세팅

✔ 구글링을 통해 form 요소 작성 (스크립트 너무 어렵다..)
✔ 해당 html, script와 따로작성한 css로 이미지 결과 도출

<input type="button" value="구매하기" onClick="alert('구매완료되었습니다')">

✅html
1) button 태그에 onClick="alert('원하는 메시지")" 작성하기

'Coding > html' 카테고리의 다른 글

[html] 웹사이트 구글지도 띄우기  (0) 2022.06.17
[html] 반응형 만들때 주의할 점  (0) 2022.05.11
<section class="sec2">
        <div class="Tbox">
            <h3>
                타이틀
            </h3>
            <h3>
                제목
            </h3>
            <p>
               내용
            </p>
        </div>
        <div class="imgBox">
            <div class="img1">
               이미지
            </div>
            <div class="img2">
               이미지
            </div>
            <div class="img3">
                이미지
            </div>
            <div class="img4">
                이미지
            </div>
        </div>
    </section>

✅html
1) sticky로 배경이 될 텍스트 작성
2) 상단으로 올라갈 이미지 작성

.sec2 {
    display: flex;
    justify-content: space-between;
    padding: 40px 0 20px 0;
}
.sec2 .Tbox {
    position: sticky;
    top: 25%;
    height: fit-content;
    padding-bottom: 50px;
}

.sec2 .imgBox {
    width: 45%;
}

.sec2 .imgBox div[class^="img"] {
    background-size: contain;
    height: 400px;
    text-indent: -9999px;
    overflow: hidden;
    margin: 15px 5px;
}

✅css / position sticky이용하여 스크롤시 좌측 텍스트는 고정하고 우측 이미지 움직이기
1) flex로 가로 배치
2) 좌측 고정될 텍스트에 position sticky 선언
3) 우측으로 올라갈 이미지 작성
4) 각 이미지 사이즈 조정, 텍스트 숨기기

.sec2 {
    flex-direction: column;
}
.sec2 .imgBox {
    width: 100%;
    backdrop-filter: blur(1.5px);
    box-shadow: 0 0 30px 30px rgba(255, 255, 255, 0.5);
    background: rgba(255, 255, 255, 0.5);
}

.sec2 .imgBox div[class^="img"] {
    height: 300px;
}

.sec2 .Tbox {
    z-index: -1;
}

✅css / position sticky이용하여 스크롤시 텍스트가 배경으로 깔리고 이미지 덮기
1) flex로 세로 배치
2) 배경으로 덮을 이미지에 filter blur처리하여 텍스트 흐리게 하기
3) 이미지 크기 조절하기
4) 텍스트 부분 z-index를 -1로 이미지보다 뒤에 위치하게 하기


✔ sticky 이용하여 유동적인 고정가능

css keyframe 이용하여 svg 파일 일부를 회전, 확대하는 애니메이션 만들기

<svg version="1.1" id="path" xmlns="http://www.w3.org/2000/svg"
                                xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 500 500"
                                style="enable-background:new 0 0 500 500;" xml:space="preserve">
                                <rect id="square" x="108.58" y="108.58"
                                    transform="matrix(0.7071 -0.7071 0.7071 0.7071 -103.5534 250)" class="st0"
                                    width="282.84" height="282.84" />
                                <line id="line_x5F_up" class="st0" x1="250" y1="10" x2="250" y2="250" />
                                <line id="line_x5F_right" class="st0" x1="490.85" y1="250" x2="250.85" y2="250" />
</svg>

✅Illustration에서 svg 가져오기 / html
1) 일러스트로 원하는 파일 제작하기
2) 각 레이어별 애니메이션을 지정하기 쉽도록 레이어 이름 설정해주기
3) svg파일을 가져와 text를 복사해서 html에 붙여 넣기

.st0 {
    fill: none;
    stroke: #FFFFFF;
    stroke-miterlimit: 10;
}

#path{
    width: 600px;
    height: 600px;
}
#line_x5F_up {
    animation-duration: 3s;
    animation-iteration-count: infinite;
    animation-fill-mode: forwards;
    transform-origin: center ;
    animation-name: circle;
}

@keyframes circle {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}
@keyframes scale {
    from{
        transform: scale(0);
    }
    to{
        transform: scale(2);
    }
}
@keyframes circle2 {
    0%{transform: rotate(0deg)}
    25%{transform: rotate(45deg)}
    50%{transform: rotate(90deg)}
    75%{transform: rotate(135deg)}
    100%{transform: rotate(180deg)}
}

✅css
1) 기존 svg에 있던 style 태그를 복사하여 css에 붙여 넣기(html 길이 줄이기 위해)
2) 전체 크기 조정을 위해 id path의 가로와 세로를 지정
3) id line up에 애니메이션 설정을 추가
- animation-duration: 애니메이션이 동작하는 시간(s:초);
- animation-iteration-count: 애니메이션 동작 횟수(infinite:무한);
- animation-fill-mode: 애니메이션 마지막 상태 설정(forwards: 마지막 동작상태 유지);
- transform-origin: transform 작동하는 기준점 (center:중앙 대지를 기준) ;
- animation-name: 동작하고 싶은 애니메이션 이름(circle: 동작할 keyframe명);
4-1) keyframe명 circle을 지정하고 회전 애니메이션을 추가한다
0도 에서 360도로 rotate(회전)하는 transform을 추가
4-2) keyframe명 scale을 지정하고 확대 애니메이션을 추가한다
0에서 2배로 scale(확대 또는 축소)하는 transform을 추가
4-3) keyframe명 circle2를 지정하고 사각형 4각에 맞춰 회전 애니메이션을 추가한다
100을 4로 나누어 %마다 transform 각도를 지정

✔ svg내에 레이어 고정과 레이어 애니메이션이 함께 있으면 html내에 텍스트로 가져와야한다
✔ svg 모든 애니메이션이 한번에 움직일때는 svg파일을 불러와도 된다

로그인창 아이디나 비밀번호 미입력시 하단에 경고문구 뜨게하기

<form action="#" method="post" name="login">
 <fieldset>
  <legend>Log In</legend>
  <input type="text" placeholder="ID 아이디" maxlength="20" name="id" id="
  <br>
  <input type="password" placeholder="PW 비밀번호" maxlength="20" name="pw" id="
  <br>
  <input type="submit" value="확인">
  <br>
  <span class="message" id="message"></span>
  </fieldset>
</form>


✅html
1) form 태그를 작성
2) 아이디, 패스워드, 확인 버튼 생성
3) 하단에 빈 span태그를 작성해준다
4) span태그에 class와 id명을 설정하여 css에서 속성과 javascript에서 속성을 설정 할 수 있게한다


window.onload = function() {
    var login = document.login;
    login.onsubmit = function() {
        if(!login.id.value){
            span = document.getElementById("message");
            txt = document.createTextNode("아이디를 입력해주세요");
            span.appendChild(txt);
            login.id.focus();
            return false;
        }
        if(!login.pw.value){
            span = document.getElementById("message");
            txt = document.createTextNode("비밀번호를 입력해주세요");
            span.appendChild(txt);
            login.pw.focus();
            return false;
        }
        else{
            span = document.getElementById("message");
            txt = document.createTextNode("잘못입력하였습니다. 아이디와 비밀번호를 확인해주세요");
            span.appendChild(txt);
            login.id.focus();
            return false;
        }
    }
}

✅Java script 방법1 ->실패
1) window.onload 함수를 선언
2) login객체를 선언
3) login 함수를 작성 if문을 활용
4) 부정문(!)을 활용하여 로그인 작성안할경우 결과값을 입력
5) if문을 만족할 경우 span에 텍스트 생성과 아이디칸에 포커스가 잡힐 수 있게 객체 생성
6) true 페이지로 넘어가지 않게 false를 반환
*pw 부분도 동일

7) else는 if문 의외의 상황시 발생
8) 성공시 페이지가 넘어가지 않도록 잘못입력하였다는 메시지와 false반환
-> 무한 flase로 계속 해서 span이 반복됨

✔️span이 확인을 누르면 무한 반복
✔️결과 값을 경고창 형식으로 바꾸고 함수를 빠져나갈 수 있게 성공 경로를 작성할 예정

 

function validate() {
    const regId = /^[a-zA-Z0-9]{4,12}$/;
    // 아이디 정규식
    const regPw = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/;
    // 패스워드 정규식, 최소 8 자, 최소 하나의 문자, 하나의 숫자 및 하나의 특수 문자
    const regNull  = /\s/g;
    // 빈값
    
    let id = document.getElementById("id");
    let pw = document.getElementById("pw");
    // 정규식 조건에 위배되었을 때, alert이 출력되는 함수였다.
    // 요 값이 true이고 이걸 부정한 조건(false)일 때 넘어간다.

    // 아이디 정규식 확인
    if (!checkReg(regId, id, "아이디는 4~12자의 영문 대소문자와 숫자로만 입력")) {
        return false;
    }

    // 비밀번호 정규식 확인
    if (!checkReg(regPw, pw, "최소 8자, 최소 하나의 문자, 숫자, 특수 문자를 포함하여 입력")) {
        return false;
    }
    // 비밀번호 빈값확인
    if (!checkNull(pw, "비밀번호를 입력해 주세요")) {
        return false;
    }
}
// 정규식 확인
function checkReg(reg, what, message) {
    // 정규식에 위배되지 않았을때
    let alertMSG = what.parentNode.lastElementChild;
    if (reg.test(what.value)) {
        alertMSG.textContent = ""; // 메시지 공백화
        return true;
    }
    // 정규식에 위배되었을때
    alertMSG.textContent = message; // 메시지 출력
    what.value = ""; // 해당 위치 공백화
    what.focus(); // 해당위치로 포커싱
}
// 빈값 확인
function checkNull(what, message) {
    // 빈값없음
    let alertMSG = what.parentNode.lastElementChild;
    if (what.value !== "") {
        alertMSG.textContent = "해당페이지는 포트폴리오 사이트로 로그인 할 수 없습니다";
        return true;
    }
    // 빈값확인
    alertMSG.textContent = message; // 메시지 출력
    what.focus(); // 해당위치로 포커싱
}


let inputs = document.querySelectorAll('input');
Array.from(inputs).forEach((eachInput) => {
    eachInput.addEventListener('blur', (e) => validate(e));
});
const validation = document.querySelector('#validation');
validation.addEventListener('click', (e) => validate(e));

✅Java script 방법2 ->성공
1)아이디, 패스워드, 빈값에 대한 정규식 작성
2) 아이디 패스워드 선언
3) id 정규식확인 if문 작성 
4) pw 정규식확인 if문 작성 
5) if문을 만족할 경우 공백화, 포커싱을 작성(무한 span방지를 위해 공백화작성)

✔️span이 확인을 누르면 무한 반복해결
✔️빈칸 뿐 아니라 정규식에 대한 부분 오류 메시지 작성

✔️ 하단 let const부분 한번 더 보기

100vh와 100%를 이용하여 콘텐츠 흐름에 따라 배경이 따라갈 수 있게 제작하기

<section class="wrap">
 <div class= "main">
  컨텐츠
 </div>
</section>

✅html
1) 배경을 넣을 section에 클래스명 wrap선언
2) div로 콘텐츠 내용을 작성 후 클래스명 main선언

.wrap {
 background: black;
 height: 100%;
}
.main{
 min-height: 100vh;
}

✅css
1-1) wrap에 배경 색을 넣어준다
1-2) 높이 100%를 지정해준다

2-1) main 콘텐츠 최대 높이를 100vh로 지정해준다

✔️배경 높이를 100% 콘텐츠 높이를 100vh 설정 시 콘텐츠 높이보다 화면 높이가 작아지면 스크롤이 생기며 배경 높이가 따라오지 못함
✔️배경 높이를 100vh 콘텐츠 높이를 100% 설정 시 콘텐츠 높이가 화면 높이보다 작으면 배경 높이가 콘텐츠에 맞춰져 하단에 빈 공간이 생김
✔️ 높이가 아닌 최소 높이를 100vh를 설정하여 해결

반응형 태그를 작성해도 테블릿 모바일 버전이 먹히지 않을때

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0">
    <link rel="stylesheet" type="text/css" href="/메인css파일경로.css">
    <link rel="stylesheet" type="text/css" media="all and (max-width: 1199px)" href="/테블릿버전css파일경로.css">
    <link rel="stylesheet" type="text/css" media="all and (max-width: 760px)" href="/모바일버전css파일경로.css">
</head>

✅html
1) head태그에 반응형용 태그를 작성한다
2) 기존 css를 연결한다( 연결되어 있다면 꼭 반응형css보다 위에 위치)
3) 테블릿과 모바일 버전의 css를 연결한다

✔️ head태그 안에 작성
✔️ 기존 css보다 반응형 css가 하단에 와야한다! 위에서 아래로 읽히기때문
✔️ css height, min과 같은 고정값을 사용할때 반응형이 어려울 수 있으니 주의해서 사용

'Coding > html' 카테고리의 다른 글

[html] 웹사이트 구글지도 띄우기  (0) 2022.06.17
[html] 버튼 클릭 시 alert메시지 띄우기  (0) 2022.06.15

css에서 position값을 이용할 때 중앙 정렬할 때 사용!
가로 세로 모두 중앙 정렬된다

.className{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
}

✅css
1) 포지션 속성을 입력한다
2) top 50%를 설정해준다
3) left 50%를 설정해준다
4) transform을 이용해서 translate의 x축 y축 값을 지정한다
5) IE에서도 적용시키기 위해 -ms-추가하여 transform을 한번 더 작성해준다

✔️ position은 좌상단을 기준점으로 이동한다
✔️ transform에 -를 넣는 이유는 내려온 만큼의 반을 다시 올라가고 오른쪽 이동만큼의 반을 다시 왼쪽으로 이동하게 하여 중앙에 맞추기 위해!

+ Recent posts