Heim > Web-Frontend > CSS-Tutorial > Hauptteil

Wichtige HTML- und CSS-Tricks zum Verzicht auf JavaScript

Patricia Arquette
Freigeben: 2024-10-17 23:34:29
Original
450 Leute haben es durchsucht

Lassen Sie uns darüber sprechen, wann Sie JavaScript nicht verwenden sollten und warum HTML und CSS oft die besseren Tools für diese Aufgabe sein können. Das klingt vielleicht kontraintuitiv – vor allem, wenn es von einem Javascript-Entwickler kommt –, aber am Ende wird es Sinn ergeben, vertrauen Sie mir!

Ich bin kein Anti-JavaScript. Ich schreibe den ganzen Tag darin für einen Rich-Text-Editor. Aber im Laufe der Zeit habe ich herausgefunden, dass ich durch die Verwendung von HTML und CSS für viele Aufgaben meinen Code tatsächlich einfacher, wartbarer und oft auch leistungsfähiger machen kann. Dieser Ansatz basiert auf einem Kernprinzip der Webentwicklung, das als die Regel der geringsten Macht bekannt ist.

Die Herrschaft der geringsten Macht

Die Regel der geringsten Macht ist einfach: Verwenden Sie die am wenigsten mächtige Sprache, die für die Aufgabe geeignet ist. In der Webentwicklung bedeutet dies, wo immer möglich, HTML statt CSS und CSS statt JavaScript zu verwenden. Die Logik hier ist:

  • HTML ist deklarativ und leichtgewichtig und eignet sich hervorragend zum Strukturieren von Inhalten.
  • CSS ist ebenfalls deklarativ und wird für das Styling verwendet. Es bietet viele Layout- und Interaktionsoptionen, für die kein JavaScript erforderlich ist.
  • JavaScript ist zwar leistungsstark, führt jedoch zu Komplexität, Leistungseinbußen und potenziellen Fehlern.

Lassen Sie uns also in einige Beispiele aus der Praxis eintauchen, die alle in diesem GitHub-Repository verfügbar sind, wo Sie normalerweise JavaScript verwendet haben, aber mit nur HTML und CSS bessere Ergebnisse erzielen können. Diese Beispiele zeigen, wie Sie Ihren Code vereinfachen und gleichzeitig Funktionalität und Leistung beibehalten können.

Beispiel 1: Benutzerdefinierte Schalter (Kontrollkästchen ohne JS)

Wir haben alle maßgeschneiderte Schalter gebaut. Normalerweise erfordert dies eine Menge JavaScript, um Klicks zu verarbeiten und Zustände umzuschalten. Aber so können Sie mit nur HTML und CSS einen voll funktionsfähigen, barrierefreien Switch erstellen.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

HTML

<label class="switch">
  <input type="checkbox" class="switch-input">
  <span class="switch-slider"></span>
</label>
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

Dieses Setup erstellt einen voll funktionsfähigen Schalter ohne JavaScript und nutzt die Pseudoklasse :checked für Stiländerungen. Diese Pseudoklasse zielt auf das Element (das Kontrollkästchen) ab, wenn es sich im Status „aktiviert“ befindet. Es löst die Stiländerungen für den Schalter aus, z. B. das Ändern der Hintergrundfarbe und das Bewegen des Schiebereglers, wenn das Kontrollkästchen aktiviert ist.

Warum das besser ist:

  • Kein JavaScript erforderlich:Weniger bewegliche Teile, weniger Risiko für Fehler.
  • Im Auslieferungszustand verfügbar:Sie erhalten automatisch Tastatur- und Mausunterstützung, was die Wartung erleichtert.

Beispiel 2: Automatischer Vorschlag mit

Die Funktion zur automatischen Vervollständigung wird oft mit einer Bibliothek oder benutzerdefiniertem JavaScript durchgeführt. Aber mit HTMLs Element können Sie mit minimalem Aufwand eine automatische Vorschlagseingabe erstellen.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

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>
Nach dem Login kopieren

CSS

.container {
  width: 300px; 
  display: block; 
}

input {
  padding: 10px;
  font-size: 18px;
  width: 100%;
  box-sizing: border-box;
}
Nach dem Login kopieren

Hier ist der Bietet eine Liste mit Vorschlägen, wenn der Benutzer mit der Texteingabe beginnt. Keine JavaScript-basierten Autovervollständigungsbibliotheken erforderlich.

Warum das besser ist:

  • Leicht: Es ist in den Browser integriert und daher schneller und effizienter.
  • Einfach:Keine zusätzliche JS, Abhängigkeiten oder komplexe Logik erforderlich.

Beispiel 3: Reibungsloses Scrollen mit CSS

Auf vielen Websites wurde das reibungslose Scrollen auf einer Webseite mit jQuery oder benutzerdefinierten JavaScript-Funktionen gehandhabt. Aber jetzt können wir dies mit einer einzigen CSS-Zeile erreichen.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

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>
Nach dem Login kopieren

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;
}
Nach dem Login kopieren

Wenn ein Benutzer auf den Ankerlink eines Abschnitts klickt, wird dadurch sichergestellt, dass die Seite reibungslos zu diesem Abschnitt scrollt.

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>
Nach dem Login kopieren

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;
}
Nach dem Login kopieren

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>
Nach dem Login kopieren

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);
}
Nach dem Login kopieren

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!

Das obige ist der detaillierte Inhalt vonWichtige HTML- und CSS-Tricks zum Verzicht auf JavaScript. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!