이전 포스팅에 이어 선택자에 대해 알아보겠다.
결과물은 상세설명보기 버튼을 누르면 설명이 나오고 더보기를 누르면 상세한 설명이 나온 후
상세설명 닫기를 누르면 설명이 닫아진다.
<div id="wrap">
<img src="img/kaffee-meister-BIeXZhg_7sw-unsplash.jpg" alt="">
<button class="over" id="open" onclick="showDetail()">상세설명보기</button>
<div id="desc" class="detail">
<h4>직장인이 사랑하는 아이스아메리카노</h4>
<p>
피곤한 직장인들은 아이스아메리카노 수혈을 하죠
<span class="hide">저는 일리 원두를 좋아합니다.</span>
</p>
<button id="close" onclick="closeDetail()">상세설명닫기</button>
<button class="moreView" id="moreView" onclick="moreView()">더보기</button>
</div>
</div>
<style>
* {
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
#wrap{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 600px;
margin-top: 50px;
}
#desc {
text-align: center;
}
#wrap img {max-width: 100%; height: auto; margin-bottom: 40px;}
button {
width: 160px;
height: 40px;
color: #fff;
font-size: 15px;
background: #64480a;
border: none;
margin: 20px 0;
}
#wrap .detail {
margin-top: 40px;
line-height: 1.6;
display: none;
}
.detail > button {margin-top: 20px; width: 120px; height: 34px; background: #333;}
.detail .hide {display: none;}
</style>
구조는 단순하게 짜봤다.
첫번째 상세설명보기 버튼에 클래스와 아이디 값을 각각 넣어주는데
클래스 값은 꼭 안넣어도 된다.
그리고 onClick=showDetail()로 클릭 이벤트를 생성해준다.
그리고 제목과 내용을 적되 더보기를 누르면 나타나는 내용은 클래스 hide를 준 뒤
css로 display: none으로 화면에서 안보이게 처리해준다.
그리고 상세설명보기 버튼이랑 동일하게 상세설명닫기 버튼 또한 onClick으로
closeDetail() 클릭 이벤트를 생성해주고 더보기 버튼도 onClick으로
moreView()클릭 이벤트를 생성해준다.
이때 클릭 이벤트명은 마음대로 지어주면 된다 :-)
<script>
function showDetail() {
document.getElementById('desc').style.display = 'block';
document.getElementById('open').style.display = 'none';
}
function closeDetail() {
document.getElementById('desc').style.display = 'none';
document.getElementById('open').style.display = 'block';
}
function moreView() {
document.getElementsByClassName('hide')[0].style.display = 'block';
}
</script>
그리고 동작을 실행시킬건데 function showDetail()로 실행 시키고
document.getElementById()로 앨리먼트를 잡아와준다.
그리고 .style.을 사용하면 자바스크립트를 이용해서 css를 수정할 수 있기에
.style.display = 'block'; > css를 수정할건데 display를 block으로 바꿔줘 라고 선언한 것이다.
이하 알맞은 상태에 맞게 선언해주고 document.getElementsByClassName은
배열 타입으로 출력되기에 혹시 모르니 [0]으로 0번째를 가져오라고 선언해준다.
그러면 간단하게 클릭하면 상세 설명글이 나오는 작업물을 만들 수 있다.
'javascript' 카테고리의 다른 글
Ajax에 대해 (0) | 2024.01.23 |
---|---|
javascript - DOM과 메소드 (2) | 2023.12.07 |
자바스크립트 switch문 (1) | 2023.12.03 |
자바스크립트 if문(2) (1) | 2023.12.03 |
자바스크립트 if문(1) (2) | 2023.12.03 |