>  기사  >  웹 프론트엔드  >  JavaScript를 버리기 위한 필수 HTML 및 CSS 요령

JavaScript를 버리기 위한 필수 HTML 및 CSS 요령

Patricia Arquette
Patricia Arquette원래의
2024-10-17 23:34:29453검색

JavaScript를 사용하지 말아야 할 경우와 왜 HTML과 CSS가 작업에 더 나은 도구가 될 수 있는지 이야기해 보겠습니다. 특히 Javascript 개발자의 경우에는 반직관적으로 들릴 수도 있지만 결국에는 이해가 될 것입니다. 저를 믿으세요!

저는 자바스크립트 반대자가 아닙니다. 리치 텍스트 편집기를 위해 하루 종일 글을 씁니다. 그러나 시간이 지남에 따라 많은 작업에 HTML과 CSS를 사용하면 실제로 코드를 더 간단하고 유지 관리하기 쉽고 성능도 더 높일 수 있다는 것을 알게 되었습니다. 이 접근 방식은 최소 전력의 법칙이라고 알려진 핵심 웹 개발 원칙에 뿌리를 두고 있습니다.

최소 전력의 법칙

최소 전력의 규칙은 간단합니다. 작업에 적합한 가장 강력한 언어를 사용하는 것입니다. 웹 개발에서 이는 가능한 경우 CSS 대신 HTML을 사용하고 JavaScript 대신 CSS를 사용하는 것을 의미합니다. 여기서의 논리는 다음과 같습니다.

  • HTML은 선언적이고 가벼우며 콘텐츠 구조화에 적합합니다.
  • CSS도 선언적이며 스타일 지정에 사용되며 JavaScript가 필요하지 않은 다양한 레이아웃 및 상호 작용 옵션을 제공합니다.
  • JavaScript는 강력하기는 하지만 복잡성, 성능 비용 및 잠재적인 오류를 초래합니다.

이제 GitHub 저장소에서 사용할 수 있는 몇 가지 실제 사례를 살펴보겠습니다. 일반적으로 JavaScript를 사용했지만 HTML 및 CSS만으로 더 나은 결과를 얻을 수 있습니다. 이 예는 기능과 성능을 유지하면서 코드를 단순화할 수 있는 방법을 보여줍니다.

예 1: 사용자 정의 스위치(JS가 없는 체크박스)

우리는 모두 맞춤형 스위치를 제작했습니다. 일반적으로 여기에는 클릭 및 토글 상태를 처리하기 위해 많은 JavaScript가 필요합니다. 그러나 HTML과 CSS만 사용하여 모든 기능을 갖춘 액세스 가능한 스위치를 구축하는 방법은 다음과 같습니다.

ssential HTML and CSS Tricks to Ditch JavaScript

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의 요소를 사용하면 최소한의 노력으로 자동 제안 입력을 생성할 수 있습니다.

ssential HTML and CSS Tricks to Ditch JavaScript

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;
}

여기서 사용자가 텍스트 입력에 입력을 시작할 때 제안 목록을 제공합니다. JavaScript 기반 자동완성 라이브러리가 필요하지 않습니다.

이것이 더 나은 이유:

  • 경량: 브라우저에 내장되어 있어 더 빠르고 효율적입니다.
  • 간단함: 추가 JS, 종속성 또는 복잡한 논리가 필요하지 않습니다.

예 3: CSS를 사용한 부드러운 스크롤

많은 웹사이트에서는 웹페이지의 부드러운 스크롤이 jQuery나 맞춤 JavaScript 기능으로 처리되었습니다. 하지만 이제는 CSS 한 줄로 이를 달성할 수 있습니다.

ssential HTML and CSS Tricks to Ditch JavaScript

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

and elements that give us this functionality with no extra code.

ssential HTML and CSS Tricks to Ditch JavaScript

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.

ssential HTML and CSS Tricks to Ditch JavaScript

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바스크립트 사용 사례다음 기사:없음