찾다
웹 프론트엔드CSS 튜토리얼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만 사용하여 모든 기능을 갖춘 액세스 가능한 스위치를 구축하는 방법은 다음과 같습니다.

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>
<option value="Open Source">
  </option>
<option value="Open Source Software">
</option></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 id="Section">Section 1</h2>
</section>

<!-- Section 2 -->
<section id="section2">
  <h2 id="Section">Section 2</h2>
</section>

<!-- Section 3 -->
<section id="section3">
  <h2 id="Section">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

     <!-- 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 id="Welcome-to-Section">Welcome to Section 1</h2>
    </section>

    <!-- Section 2 -->
    <section id="section2">
        <h2 id="Welcome-to-Section">Welcome to Section 2</h2>
    </section>

    <!-- Section 3 -->
    <section id="section3">
        <h2 id="Welcome-to-Section">Welcome to Section 3</h2>
    </section>

    <!-- Section 4 -->
    <section id="section4">
        <h2 id="Welcome-to-Section">Welcome to Section 4</h2>
    </section>

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으로 문의하세요.
@keyframes 및 @Media와 같이 @Rules는 얼마나 많은 특이성을 가지고 있습니까?@keyframes 및 @Media와 같이 @Rules는 얼마나 많은 특이성을 가지고 있습니까?Apr 18, 2025 am 11:34 AM

나는 다른 날이 질문을 받았다. 나의 첫 번째 생각은 : 이상한 질문입니다! 특이성은 선택기에 관한 것이며 At-Rules는 선택기가 아니므로 ... 무의미합니까?

@Media 및 @Support 쿼리를 중첩 할 수 있습니까?@Media 및 @Support 쿼리를 중첩 할 수 있습니까?Apr 18, 2025 am 11:32 AM

그렇습니다. 당신은 할 수 있습니다. 그리고 그것은 실제로 어떤 순서로 중요하지 않습니다. CSS 전 처리기가 필요하지 않습니다. 일반 CSS에서 작동합니다.

빠른 Gulp 캐시 파열빠른 Gulp 캐시 파열Apr 18, 2025 am 11:23 AM

CSS 및 JavaScript (및 이미지 및 글꼴 등)와 같은 자산에 멀리 떨어진 캐시 헤더를 설정해야합니다. 브라우저를 알려줍니다

CSS의 품질과 복잡성을 모니터링하는 스택을 찾아CSS의 품질과 복잡성을 모니터링하는 스택을 찾아Apr 18, 2025 am 11:22 AM

많은 개발자들은 CSS 코드베이스를 유지하는 방법에 대해 글을 썼지 만 코드베이스의 품질을 어떻게 측정하는지에 대해 많은 글을 쓰지 않습니다. 물론, 우리는 가지고 있습니다

Datalist는 가치를 시행하지 않고 값을 제안하는 것입니다Datalist는 가치를 시행하지 않고 값을 제안하는 것입니다Apr 18, 2025 am 11:08 AM

짧고 임의의 텍스트를 수락 해야하는 양식이 있습니까? 이름이나 다른 것 같습니다. 정확히 무엇을위한 것입니다. 많은 것이 있습니다

취리히에서 열린 전면 회의취리히에서 열린 전면 회의Apr 18, 2025 am 11:03 AM

나는 프론트 컨퍼런스를 위해 스위스 취리히로 향하게되어 매우 기쁩니다 (그 이름과 URL을 사랑합니다!). 나는 전에 스위스에 가본 적이 없기 때문에 나는 흥분했다

CloudFlare Workers와 함께 풀 스택 서버리스 애플리케이션 구축CloudFlare Workers와 함께 풀 스택 서버리스 애플리케이션 구축Apr 18, 2025 am 10:58 AM

소프트웨어 개발에서 제가 가장 좋아하는 개발 중 하나는 서버리스의 출현이었습니다. 세부 사항에 푹 빠지는 경향이있는 개발자로서

NUXT 응용 프로그램에서 동적 경로 생성NUXT 응용 프로그램에서 동적 경로 생성Apr 18, 2025 am 10:53 AM

이 게시물에서는 들어오는 데이터를 위해 동적 경로를 만드는 방법을 보여주기 위해 NetLify에 구축하고 배포 한 전자 상거래 상점 데모를 사용합니다. 상당히입니다

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경