HTML, CSS 및 자바스크립트를 사용하여 필터 기능을 사용하여 응답 양식...

HTML, CSS 및 자바스크립트를 사용하여 필터 기능을 사용하여 응답 양식...

반응형

테이블에 데이터 목록을 표시하는 대부분의 사이트에는 일반적으로 일종의 필터 기능이 구현되어 있습니다. 이렇게 하면 양식 입력에 입력하는 텍스트를 기준으로 관련 항목을 필터링할 수 있습니다.

이 빠른 튜토리얼에서는 다음과 같은 반응성 필터 가능 표를 만들 것입니다.

테이블에는 개발자 목록이 포함됩니다. 각 행에는 이름, 사용 기간 및 프로그래밍 언어가 포함됩니다. 사용자가 입력 필드에 입력하면 테이블은 입력한 값과 일치하는 행을 필터링하고 반환합니다.

이 기능을 구축하는 과정에서 일부 CSS 속성과 자바스크립트를 사용한 DOM 액세스/조작에 대해 배우게 됩니다.

코드펜에서 예제 코드를 가져올 수 있습니다.

시작하기

프로젝트 폴더에 세 개의 간단한 파일을 만들어야 합니다. HTML 마크업의 경우 index.html, 스타일링의 경우 styles.css, 스크립트의 경우 index.js이다.

Filterable Table

위의 HTML에서와 같이 스타일시트와 스크립트 파일을 링크하는 것을 잊지 마세요.

표에 대한 HTML 마크업

본문 태그 안에 다음 마크업을 추가합니다.

Name Age Language Kingsley 32 JavaScript Samuel 22 Python Joyce 28 Ruby Jake 29 Python Daniel 40 JavaScript Mary 21 C David 26 JavaScript Kelly 31 React Cleo 43 Java Peter 19 Vue George 59 Cobol James 29 JavaScript Ethan 22 PHP Sandra 29 R Pires 34 React Native Martha 30 React

첫 번째 요소는 양식 입력입니다. 사용자로부터 데이터를 수집할 때 사용합니다.

그럼 식탁에 앉으세요. 테이블은 머리(시어드)와 몸체(몸체)로 구성됩니다. 머리에는 표제인 데이터의 단일 행(tr)이 있습니다. 본문에는 이름, 나이, 프로그래밍 언어로 구성된 16개의 행의 데이터가 있습니다.

이 두 요소를 모두 부모 div 태그로 포장합니다. CSS의 뒷부분에서 볼 수 있듯이 그들은 우리가 정렬하는 것을 도울 것이다.

파일을 저장하고 웹 브라우저에서 앱을 엽니다.

CSS를 사용하여 테이블을 스타일링하는 방법

이제 테이블에 스타일링을 적용하겠습니다. 먼저 기본 스타일을 다음과 같이 설정합니다.

@import url("https://fonts.googleapis.com/css2?family=Lato:wght@300&display;=swap"); /* Set no margin and padding around body. Set height to take up entire screen height. Align everything to the center, both horizontally and vertically */ body { margin: 0; height: 100vh; padding: 0; font-family: "lato", sans-seriff; display: grid; justify-content: center; align-items: center; font-size: 20px; } /* Remove border and outline around input. Set width to take up the entire width of parent and set margin on bottom */ #searchInput { border: none; outline: none; width: 100%; margin-bottom: 20px; } /* When input gains focus, add a blue border below it */ #searchInput:focus { border-bottom: 2px solid #4575b6; }

테이블이 중앙에 정렬됩니다.

테이블을 더 보기 좋게 만들기 위해 다음 스타일링 규칙을 사용할 수 있습니다.

/* Sets width of table container (div) to 80% of browser window's width and the height to 100% of window's height. `vh` and `vw` makes the table responsive because it scales along with screen size. Also set margin of 20px to top and bottom */ .app { width: 80vw; height: 100vh; margin: 20px 0; } /* Collapse all borders separating each cell. Table takes up entire width of .app. Set gray shadow around table */ table { border-collapse: collapse; width: 100%; box-shadow: 0 5px 7px gray; } /* Set shadow on just the table head */ thead { box-shadow: 0px 0px 10px gray; } /* Add some space around table heading. Align text to right and transform to uppercase */ th { padding: 1rem 3rem; text-transform: uppercase; letter-spacing: 1px; text-align: left; } /* Add padding on each cell */ td { padding: 0.5rem 3rem; font-size: 1rem; } /* Create alternating color(blue) across the rows. Set blue on all even ones (2, 4, 6 ...) */ tr:nth-child(even) { background-color: #dee8f5; }

이제 우리의 테이블은 좀 더 좋아보이고 반응도 좋습니다.

자바스크립트를 통한 필터 기능 구현 방법

이 시점에서 테이블은 거의 움직이지 않는다. 자바스크립트를 사용하여 사용자가 양식 필드에 입력하는 내용에 따라 이름을 필터링하는 논리를 구현합니다.

스크립트 파일에서 필터라는 함수를 정의합니다. 처음 세 행에서는 사용자의 입력 값에 액세스하고, 테이블 본문를 변수 이름으로 전달하며, 마지막으로내부에서 모든 테이블 행에 액세스한다.

또한 모든 값이 일치하는지 확인하기 위해 값을 대문자로 변경합니다(사용자는 J 대신 j 를 입력할 수 있음).

/* This function will check for the user's input and based on that will either hide or display a particular row */ function filter() { // Access text value and elements from the DOM let value = document.getElementById("searchInput").value.toUpperCase(); let names = document.getElementById("names"); let rows = names.getElementsByTagName("tr"); // Code continues

그런 다음 각 어레이를 반복하여 살펴봅니다. 각 행에 대해 마지막 열(언어 열)에 액세스하여 텍스트 내용(실제 값)을 가져옵니다.

for (i = 0; i < rows.length; i++) { let column = rows[i].getElementsByTagName("td")[2]; let language = column.textContent; rows[i].style.display = language.toUpperCase().indexOf(value) > -1 ? "" : "none"; } } document.getElementById("searchInput").addEventListener("keyup", filter);

테이블 행 반복

테이블의 실제 문자열 값에 사용자의 입력 값이 포함된 경우 해당 행을 표시합니다. 그렇지 않으면, 우리는 그것을 숨깁니다. 우리는 또한 조건부 진술을 단축하기 위해 3항 연산자를 사용했다.

마지막으로 입력에 이벤트 수신기를 추가합니다. 키를 놓을 때마다 필터가 호출됩니다.

다음은 이에 대한 전체 코드입니다.

function filter() { let value = document.getElementById("searchInput").value.toUpperCase(); var names = document.getElementById("names"); var rows = names.getElementsByTagName("tr"); for (i = 0; i < rows.length; i++) { let column = rows[i].getElementsByTagName("td")[2]; let language = column.textContent; rows[i].style.display = language.toUpperCase().indexOf(value) > -1 ? "" : "none"; } } document.getElementById("searchInput").addEventListener("keyup", filter);

표가 마지막에 이것과 비슷해야 합니다.

마무리하기

HTML, CSS 및 JavaScript만으로 고급 기능을 갖춘 매우 세련된 요소를 만들 수 있습니다.

이것에서 한 두 가지만 배웠으면 좋겠어요. 다시 한 번, 코드펜에서 코드를 확인하고 원하는 대로 수정할 수 있습니다.

따라와 주셔서 감사합니다.

from http://information-bada.tistory.com/49 by ccl(A) rewrite - 2021-10-16 05:01:13