検索

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 src="/static/imghwm/default1.png" data-src="image.jpg" class="lazy" 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 src="/static/imghwm/default1.png" data-src="image.jpg" class="lazy" data- 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><a></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?

以上がクリック時に画像を表示する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
@keyframesや@mediaなど、 @rulesにはどの程度の特異性がありますか?@keyframesや@mediaなど、 @rulesにはどの程度の特異性がありますか?Apr 18, 2025 am 11:34 AM

先日、この質問がありました。私の最初の考えは、奇妙な質問です!特異性はセレクターに関するものであり、アットレールはセレクターではないので、...無関係ですか?

@mediaと@supportのクエリをネストできますか?@mediaと@supportのクエリをネストできますか?Apr 18, 2025 am 11:32 AM

はい、あなたはできます、そしてそれは本当にどの順序で重要ではありません。 CSSプリプロセッサは必要ありません。通常のCSSで動作します。

クイックガルプキャッシュバストクイックガルプキャッシュバストApr 18, 2025 am 11:23 AM

CSSやJavaScript(および画像とフォントなど)などのアセットにファーアウトキャッシュヘッダーを確実に設定する必要があります。それはブラウザを伝えます

CSSの品質と複雑さを監視するスタックを探してCSSの品質と複雑さを監視するスタックを探してApr 18, 2025 am 11:22 AM

多くの開発者は、CSSコードベースを維持する方法について書いていますが、そのコードベースの品質をどのように測定するかについて多くの人が書いていません。確かに、私たちは持っています

データリストは、値を強制せずに値を提案するためのものですデータリストは、値を強制せずに値を提案するためのものですApr 18, 2025 am 11:08 AM

短い任意のテキストを受け入れるために必要なフォームを持っていたことがありますか?名前などのように。それはまさにそのためのものです。たくさんあります

チューリッヒでのフロント会議チューリッヒでのフロント会議Apr 18, 2025 am 11:03 AM

私は、フロント会議のためにスイスのチューリッヒに向かうことにとても興奮しています(その名前とURLが大好きです!)。私はこれまでスイスに行ったことがないので、興奮しています

CloudFlareワーカーとのフルスタックサーバーレスアプリケーションを構築しますCloudFlareワーカーとのフルスタックサーバーレスアプリケーションを構築しますApr 18, 2025 am 10:58 AM

ソフトウェア開発における私のお気に入りの開発の1つは、サーバーレスの出現です。詳細に行き詰まる傾向がある開発者として

NUXTアプリケーションで動的ルートを作成しますNUXTアプリケーションで動的ルートを作成しますApr 18, 2025 am 10:53 AM

この投稿では、私が構築して展開して展開してネットライフを使用して、着信データの動的ルートを作成する方法を示すeコマースストアのデモを使用します。それはかなりです

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ヘンタイを無料で生成します。

ホットツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター