国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table des matières
Method #2: Using links to create an image
Maison interface Web tutoriel CSS Comment afficher des images en clic

Comment afficher des images en clic

Mar 23, 2025 am 09:15 AM

How to Show Images on Click

Most images on the web are superfluous. If I might be a jerk for a bit, 99% of them aren’t even that helpful at all (although there are rare exceptions). That’s because images don’t often complement the text they’re supposed to support and instead hurt users, taking forever to load and blowing up data caps like some sort of performance tax.

Thankfully, this is mostly a design problem today because making images performant and more user-friendly is so much easier than it once was. We have better image formats likeWebP(and soon, perhaps,JPEG XL). We have the magic ofresponsive imagesof course. And there are tons of great tools out there, like ImageOptim, as well as resources such as Addy Osmani’s new book.

Although perhaps my favorite way to improve image performance is withlazy loading:

<img href="image.webp" alt="Image description" loading="lazy">

This image will only load when a user scrolls down the page so it’s visible to the user?—?which removes it from the initial page load and that’s just great! Making that initial load of a webpage lightningfast is a big deal.

But maybe there are images that should never load at all. Perhaps there are situations where it’d be better if a person could opt-into seeing it. Here’s one example: take the text-only version ofNPRand click around for a bit. Isn’t it… just so great?! It’s readable! There’s no junk all over the place, it respects me as a user and?—?sweet heavens?—?is itfast.

So! What if we could show images on a website but only once they are clicked or tapped? Wouldn’t it be neat if we could show a placeholder and swap it out for the real image on click? Something like this:

Well, I had two thoughts here as to how to build this chap (the golden rule is that there’s never one way to build anything on the web).

Method #1: Using without a src attribute

We can remove the src attribute of an tag to hide an image. We could then put the image file in an attribute, like data-src or something, just like this:

<img data-src="image.jpg" src="" alt="Photograph of hot air balloons by Musab Al Rawahi. 144kb">

By default, most browsers will show a broken image icon that you’re probably familiar with:

Okay, so it’s sort of accessible. I guess? You can see the alt tag rendered on screen automatically, but with a light dash of JavaScript, we can then swap out the src with that attribute:

document.querySelectorAll("img").forEach((item) => {
  item.addEventListener("click", (event) => {
    const image = event.target.getAttribute("data-src");
    event.target.setAttribute("src", image);
  });
});

Now we can add some styles and ugh, oh no:

Ugh. In some browsers there’ll be a tiny broken image icon in the bottom when the image hasn’t loaded. The problem here is that browsers don’t give you a way to remove the broken image icon with CSS (and we probably shouldn’t be allowed to anyway). It’s a bit annoying to style the alt text, too. But if we remove the alt attribute altogether, then the broken image icon is gone, although this makes the unusable without JavaScript. So removing that alt text is a no-go.

As I said: Ugh. I don’t think there’s a way to make this method work (although please prove me wrong!).

The other option we have is to start with the humble hyperlink, like this:

<a href="image.jpg">Photograph of hot air balloons by Musab Al Rawahi. 144kb<a>

Which, yep, nothing smart happening yet?—?this will just render a link to an image:

That works accessibility-wise, right? If we don’t have any JavaScript, then all we have is just a link that folks can optionally click. Performance-wise, it can’t get much faster than plain text!

But from here, we can reach for JavaScript to stop the link from loading on click, grab the href attribute within that link, create an image element and, finally, throw that image on the page and remove the old link once we’re done:

document.querySelectorAll(".load-image").forEach((item) => {
  item.addEventListener("click", (event) => {
    const href = event.target.getAttribute("href");
    const newImage = document.createElement("img");
    event.preventDefault();
    newImage.setAttribute("src", href);
    document.body.insertBefore(newImage, event.target);
    event.target.remove();
  });
});

We could probably style this placeholder link to make it look a bit nicer than what I have below. But this is just an example. Go ahead and click the link to load the image again:

And there you have it! It isn’t groundbreaking or anything, and I’m sure someone’s done this before at some point or another. But if we wanted to be extremely radical about performance beyond the first paint and initial load, then I think this is an okay-ish solution. If we’re making a text-only website then I think this is definitely the way to go.

Perhaps we could also make a web component out of this, or even detect if someone hasprefers-reduced-dataand then only load images if someone has enough data or something. What do you think?

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefa?on, veuillez contacter admin@php.cn

Outils d'IA chauds

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

échangez les visages dans n'importe quelle vidéo sans effort grace à notre outil d'échange de visage AI entièrement gratuit?!

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Qu'est-ce que le ?rendu CSS bloquant le rendu?? Qu'est-ce que le ?rendu CSS bloquant le rendu?? Jun 24, 2025 am 12:42 AM

CSS bloque le rendu de la page car les navigateurs affichent le CSS en ligne et le CSS externe comme des ressources clés par défaut, en particulier avec les feuilles de styles importées, les grandes quantités de CSS en ligne et les styles de requête multimédia non optimisés. 1. Extraire CSS critique et l'intégrez-la dans HTML; 2. Retard Chargement CSS non critique via JavaScript; 3. Utilisez des attributs multimédias pour optimiser le chargement tel que les styles d'impression; 4. Comprimer et fusionner CSS pour réduire les demandes. Il est recommandé d'utiliser des outils pour extraire les CS de clé, combiner le chargement asynchrone rel = "précharge" et utiliser le chargement retardé des médias raisonnablement pour éviter une division excessive et un contr?le de script complexe.

CSS externe vs interne: quelle est la meilleure approche? CSS externe vs interne: quelle est la meilleure approche? Jun 20, 2025 am 12:45 AM

TheBestApproachForCSSDependSonTheproject'sspecificneeds.ForLargerProjects, externalcsisBetterDueTomaintainiabilityAndReUsability; ForsmallerProjectsorSingle-pageApplications, internecssigh

Mon CSS doit-il être en minuscules? Mon CSS doit-il être en minuscules? Jun 19, 2025 am 12:29 AM

NON, CSSDOOSNOTHAVETOBEINLOWLOWERCASE.CI, USING USINGERCASERASERISROMEND pour: 1) Cohérence et réadaptation, 2) évitant les technologies de perception liées à la pertinence, 3) Potentiel PerformanceBenefits, and4) Amélioration de la collaboration.

CSS Sensibilité aux cas: comprendre ce qui compte CSS Sensibilité aux cas: comprendre ce qui compte Jun 20, 2025 am 12:09 AM

CSSismostlyCase-insensible, buturlsandfontfamilyNamesaSaSase-sensible.1) Propriéties andvaluesLikEcolor: Red; arenotcase-sensible.2) UrlSMustMatchTheServer'scase, par exemple, / images / Logo.png.3) FontFamilyNamesliNe'apensans's'mUstBeexact.

Qu'est-ce que l'autoprefixer et comment ?a marche? Qu'est-ce que l'autoprefixer et comment ?a marche? Jul 02, 2025 am 01:15 AM

AutoPrefixer est un outil qui ajoute automatiquement les préfixes des fournisseurs aux attributs CSS en fonction de la portée du navigateur cible. 1. Il résout le problème de maintenir manuellement les préfixes avec des erreurs; 2. Travaillez le formulaire de plug-in PostCSS, analyse CSS, analysez les attributs qui doivent être préfixés et générer du code en fonction de la configuration; 3. Les étapes d'utilisation incluent l'installation de plug-ins, la définition de la liste de navigateurs et leur permettant dans le processus de construction; 4. Les notes ne comprennent pas manuellement les préfixes, le maintien des mises à jour de la configuration, les préfixes pas tous des attributs, et il est recommandé de les utiliser avec le préprocesseur.

Que sont les compteurs CSS? Que sont les compteurs CSS? Jun 19, 2025 am 12:34 AM

CSSCOUNTERSCANAUTOMAMATIQUE UNEUXESECTIONS ET LISTS.1) USECOUNTER-RESEDTOINITINALIALIALISE, COMPTENDREMENTTOINCREAD, andCounter () Orcounters () toDisplayValues.2) combinewithjavascriptfordynamiccontentoenSureAcurateupdates.

CSS: Quand l'affaire est importante (et quand ne pas)? CSS: Quand l'affaire est importante (et quand ne pas)? Jun 19, 2025 am 12:27 AM

Dans CSS, les noms de sélecteur et d'attribut sont sensibles à la casse, tandis que les valeurs, les couleurs nommées, les URL et les attributs personnalisés sont sensibles à la casse. 1. Les noms de sélecteur et d'attribut sont insensibles à la casse, tels que la couleur arrière et la couleur arrière-plan sont les mêmes. 2. La couleur hexadécimale de la valeur est sensible à la casse, mais la couleur nommée est sensible à la casse, comme le rouge et le rouge n'est pas valide. 3. Les URL sont sensibles à la casse et peuvent causer des problèmes de chargement de fichiers. 4. Les propriétés personnalisées (variables) sont sensibles à la caisse, et vous devez faire attention à la cohérence du cas lorsque vous les utilisez.

Quelle est la fonction conique-gradient ()? Quelle est la fonction conique-gradient ()? Jul 01, 2025 am 01:16 AM

THECONCON-GRADIENT () FURMATINGEnSSSCREATSCICLULARD GRODIENTSTHATATATECOLORSTOPSAROUNDacentralpoint.1.IiSIDEALFORPIECHARTS, PROGRESSINDICATEURS, Colorweels, andDecorativeBackgrounds.2.itworksByDefiningColOrStopSatSpiecificangles, FactuallylyTartingfromadefinin

See all articles