JavaScript를 버리기 위한 필수 HTML 및 CSS 요령
JavaScript를 사용하지 말아야 할 경우와 왜 HTML과 CSS가 작업에 더 나은 도구가 될 수 있는지 이야기해 보겠습니다. 특히 Javascript 개발자의 경우에는 반직관적으로 들릴 수도 있지만 결국에는 이해가 될 것입니다. 저를 믿으세요!
저는 자바스크립트 반대자가 아닙니다. 리치 텍스트 편집기를 위해 하루 종일 글을 씁니다. 그러나 시간이 지남에 따라 많은 작업에 HTML과 CSS를 사용하면 실제로 코드를 더 간단하고 유지 관리하기 쉽고 성능도 더 높일 수 있다는 것을 알게 되었습니다. 이 접근 방식은 최소 전력의 법칙이라고 알려진 핵심 웹 개발 원칙에 뿌리를 두고 있습니다.
최소 전력의 법칙
최소 전력의 규칙은 간단합니다. 작업에 적합한 가장 강력한 언어를 사용하는 것입니다. 웹 개발에서 이는 가능한 경우 CSS 대신 HTML을 사용하고 JavaScript 대신 CSS를 사용하는 것을 의미합니다. 여기서의 논리는 다음과 같습니다.
- HTML은 선언적이고 가벼우며 콘텐츠 구조화에 적합합니다.
- CSS도 선언적이며 스타일 지정에 사용되며 JavaScript가 필요하지 않은 다양한 레이아웃 및 상호 작용 옵션을 제공합니다.
- JavaScript는 강력하기는 하지만 복잡성, 성능 비용 및 잠재적인 오류를 초래합니다.
이제 GitHub 저장소에서 사용할 수 있는 몇 가지 실제 사례를 살펴보겠습니다. 일반적으로 JavaScript를 사용했지만 HTML 및 CSS만으로 더 나은 결과를 얻을 수 있습니다. 이 예는 기능과 성능을 유지하면서 코드를 단순화할 수 있는 방법을 보여줍니다.
예 1: 사용자 정의 스위치(JS가 없는 체크박스)
우리는 모두 맞춤형 스위치를 제작했습니다. 일반적으로 여기에는 클릭 및 토글 상태를 처리하기 위해 많은 JavaScript가 필요합니다. 그러나 HTML과 CSS만 사용하여 모든 기능을 갖춘 액세스 가능한 스위치를 구축하는 방법은 다음과 같습니다.
Github 레포
HTML
<label class="switch"> <input type="checkbox" class="switch-input"> <span class="switch-slider"></span> </label>
CSS
/* The outer container for the switch */ .switch { position: relative; display: inline-block; width: 60px; height: 34px; } /* The hidden checkbox input */ .switch-input { opacity: 0; width: 0; height: 0; } /* The visible slider (background) of the switch */ .switch-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; } /* The circle (slider button) inside the switch */ .switch-slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; } /* Pseudo-class that styles the switch when the checkbox is checked */ .switch-input:checked + .switch-slider { background-color: #2196F3; } /* Moves the slider button to the right when the switch is checked */ .switch-input:checked + .switch-slider:before { transform: translateX(26px); }
이 설정은 스타일 변경을 위해 :checked 의사 클래스를 활용하여 JavaScript 없이 완전한 기능을 갖춘 스위치를 생성합니다. 이 의사 클래스는 "선택된" 상태에 있는 요소(체크박스)를 대상으로 합니다. 체크박스가 켜져 있을 때 배경색 변경, 슬라이더 버튼 이동 등 스위치의 스타일 변경을 트리거합니다.
이것이 더 나은 이유:
- JavaScript가 필요하지 않습니다. 움직이는 부품이 적고 버그가 발생할 가능성이 적습니다.
- 즉시 액세스 가능: 키보드와 마우스가 자동으로 지원되므로 유지 관리가 더 쉽습니다.
예 2:
자동 완성 기능은 라이브러리나 맞춤 JavaScript를 사용하여 수행되는 경우가 많습니다. 하지만 HTML의
Github 레포
HTML
<input type="text" list="suggestions" placeholder="Choose an option..."> <datalist id="suggestions"> <option value="Open AI"> <option value="Open Source"> <option value="Open Source Software"> </datalist>
CSS
.container { width: 300px; display: block; } input { padding: 10px; font-size: 18px; width: 100%; box-sizing: border-box; }
여기서
이것이 더 나은 이유:
- 경량: 브라우저에 내장되어 있어 더 빠르고 효율적입니다.
- 간단함: 추가 JS, 종속성 또는 복잡한 논리가 필요하지 않습니다.
예 3: CSS를 사용한 부드러운 스크롤
많은 웹사이트에서는 웹페이지의 부드러운 스크롤이 jQuery나 맞춤 JavaScript 기능으로 처리되었습니다. 하지만 이제는 CSS 한 줄로 이를 달성할 수 있습니다.
Github 레포
HTML
<nav> <a href="#section1">Go to Section 1</a> <a href="#section2">Go to Section 2</a> <a href="#section3">Go to Section 3</a> </nav> <!-- Section 1 --> <section id="section1"> <h2>Section 1</h2> </section> <!-- Section 2 --> <section id="section2"> <h2>Section 2</h2> </section> <!-- Section 3 --> <section id="section3"> <h2>Section 3</h2> </section>
CSS
/* Basic styling for sections */ section { height: 100vh; padding: 20px; font-size: 24px; display: flex; justify-content: center; align-items: center; } /* Different background colors for each section */ #section1 { background-color: lightcoral; } #section2 { background-color: lightseagreen; } #section3 { background-color: lightblue; } /* Styling for the navigation */ nav { position: fixed; top: 10px; left: 10px; } nav a { display: block; margin-bottom: 10px; text-decoration: none; color: white; padding: 10px 20px; background-color: #333; border-radius: 5px; } nav a:hover { background-color: #555; }
사용자가 섹션의 앵커 링크를 클릭하면 페이지가 해당 섹션으로 원활하게 스크롤됩니다.
Why This Is Better:
- Less Code: Achieve smooth scrolling with a single line of CSS instead of complex JavaScript, reducing code complexity.
- Improved Performance: Native CSS scrolling is faster and more efficient than JavaScript-based solutions.
- Browser Consistency: CSS ensures smooth scrolling works consistently across browsers and devices.
Example 4: Accordions using and
Accordion menus are often built with JavaScript to toggle visibility of content. But HTML provides the elements that give us this functionality with no extra code.
Github Repo
HTML
<details> <summary>Click to toggle</summary> <p>This is some content!</p> </details>
CSS
details { width: 300px; background-color: #f9f9f9; padding: 20px; border: 1px solid #ddd; font-size: 18px; } summary { cursor: pointer; font-size: 20px; font-weight: bold; } details[open] summary { color: #2196F3; }
This simple markup gives us an interactive, accessible accordion that can open and close, without needing any JavaScript.
Why This Is Better:
- Native: It’s a browser feature, so it’s faster and more reliable.
- ** Accessible:** The browser handles focus management and interaction patterns for you.
Example 5: Scroll-Triggered Animations with CSS
Animating elements based on scroll position is often done with JavaScript libraries. But with the scroll-margin property and scroll-behavior CSS, you can create smoother, more accessible animations.
Github Repo
HTML
<body> <!-- Navigation with anchor links --> <nav style="position:fixed; top:10px; left:10px;"> <a href="#section1">Section 1</a> <a href="#section2">Section 2</a> <a href="#section3">Section 3</a> <a href="#section4">Section 4</a> </nav> <!-- Section 1 --> <section id="section1"> <h2>Welcome to Section 1</h2> </section> <!-- Section 2 --> <section id="section2"> <h2>Welcome to Section 2</h2> </section> <!-- Section 3 --> <section id="section3"> <h2>Welcome to Section 3</h2> </section> <!-- Section 4 --> <section id="section4"> <h2>Welcome to Section 4</h2> </section> </body>
CSS
html { scroll-behavior: smooth; } /* Remove body margins */ body { margin: 0; } /* Full viewport height for sections with centered content */ section { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; transition: background-color 0.6s ease-in-out; } /* Styling for headings */ section h2 { font-size: 36px; margin: 0; transition: transform 0.6s ease, opacity 0.6s ease; opacity: 0; transform: translateY(30px); } /* Add margin for scroll snapping */ section:nth-child(odd) { background-color: #ffcccb; } section:nth-child(even) { background-color: #d0e7ff; } /* Scroll-triggered animation */ section:target h2 { opacity: 1; transform: translateY(0); }
Why This Is Better
- No JavaScript required: You can achieve smooth scroll-triggered animations with just CSS.
- Performance: Animations are handled natively by the browser, leading to smoother, more efficient transitions without the complexity of JavaScript.
- Simpler to maintain: Using CSS reduces the need for complex JavaScript scroll-tracking logic, making the code easier to update and maintain.
There are plenty of cases where you can avoid the complexity of JavaScript entirely by using native browser features and clever CSS tricks.
As we see the rise of AI assistants in coding and Chat-Oriented Programming, the ability to adopt and enforce simpler, declarative solutions like HTML and CSS becomes even more crucial. AI tools can generate javascript code quickly, but leveraging HTML and CSS for core functionality ensures that the code remains maintainable and easy to understand, both by humans and AI. By using the least powerful solution for the job, you not only make your code more accessible but also enable AI to assist in a more efficient and optimized way.
HTML and CSS provide powerful tools for building interactive, accessible, and responsive web components—without the need for heavy JavaScript. So next time you’re tempted to reach for JavaScript, take a moment to consider if a simpler solution using HTML and CSS might work just as well, or even better.
Check out the Github repository for all the examples in the article. Also, check out the TinyMCE blog for insights, best practices, and tutorials, or start your journey with TinyMCE by signing up for a 14-day free trial today.
Happy coding!
위 내용은 JavaScript를 버리기 위한 필수 HTML 및 CSS 요령의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Google Fonts가 새로운 디자인 (트윗)을 출시 한 것을 볼 수 있습니다. 마지막 큰 재 설계와 비교할 때 이것은 훨씬 더 반복적 인 느낌이 듭니다. 차이를 간신히 말할 수 있습니다

프로젝트에 카운트 다운 타이머가 필요한 적이 있습니까? 그런 것은 플러그인에 도달하는 것이 당연하지만 실제로는 훨씬 더 많습니다.

플렉스 레이아웃의 보라색 슬래시 영역에 대한 질문 플렉스 레이아웃을 사용할 때 개발자 도구 (d ...)와 같은 혼란스러운 현상이 발생할 수 있습니다.

요소 수가 고정되지 않은 경우 CSS를 통해 지정된 클래스 이름의 첫 번째 자식 요소를 선택하는 방법. HTML 구조를 처리 할 때 종종 다른 요소를 만듭니다 ...

타탄은 일반적으로 스코틀랜드, 특히 세련된 킬트와 관련된 패턴의 천입니다. tartanify.com에서 우리는 5,000 개가 넘는 타탄을 모았습니다

새로운 프로젝트가 시작될 때, Sass 컴파일은 눈을 깜박이게합니다. 특히 BrowserSync와 짝을 이루는 경우 기분이 좋습니다.

Safari에서 사용자 정의 스타일 시트 사용에 대한 토론 오늘 우리는 Safari 브라우저에 대한 사용자 정의 스타일 시트 적용에 대한 질문에 대해 논의 할 것입니다. 프론트 엔드 초보자 ...
