首頁 > web前端 > js教程 > NgSysV.響應式/自適應設計

NgSysV.響應式/自適應設計

Susan Sarandon
發布: 2024-11-27 21:13:09
原創
664 人瀏覽過

NgSysV.Responsive/Adaptive Design

此貼文系列已在 NgateSystems.com 建立索引。您還可以在那裡找到超級有用的關鍵字搜尋工具。

最後評論:24 年 11 月

一、簡介

貼文 4.2 透露,如果您希望您的 web 應用程式出現在網路搜尋中,您必須確保:

  • 您的網路應用程式在手機小螢幕上查看時效果良好,並且
  • 您想要被搜尋引擎索引的所有內容都可以在行動版本上看到。

如果您的軟體主要面向桌面用戶,這是一個巨大的麻煩 - 但這就是生活。讓我們看看您如何有系統地解決這個問題。

2.使用Tailwind的響應式設計

響應式設計使用 CSS 樣式的「內建」功能來測試顯示裝置的寬度並相應地調整格式。這一切都會在瀏覽器中自動發生 - 但您仍然必須提供有關每個「斷點」(要套用新的特定於寬度的樣式的螢幕寬度)處發生的情況的明確說明。

到目前為止,您在本系列中使用的標準 CSS 樣式透過使用一種稱為「媒體查詢」的技術來實現這些自適應效果。但在這篇文章中,我將向您介紹一個名為 Tailwind 的「開放式庫」。這是為響應式樣式量身定制的,並且具有許多額外的優點。

以下是 Tailwind 樣式的範例,它將在寬度不超過 768 像素的螢幕上將居中標題限制為螢幕寬度的 95%。在此寬度之上,居中標題被限制為螢幕寬度的 60%:

<h1>



<p>Previously in this series, you've seen styles applied to HTML elements like <p> by adding>

<p>The essence of Tailwind is that it provides a system of single-purpose "utility classes", each of which applies a specific set of styles to an element. The class names are chosen judiciously to provide a meaningful and practical expression of styling intentions. The example below styles a <p> element with 4rem padding on all four sides and a  background color of light gray.<br>
</p>

<pre class="brush:php;toolbar:false"><div>



<p>Here, in bg-blue-500, bg says that this is a background style, blue sets the background colour to blue and 500 sets the colour "intensity" to a mid-value on a scale of 100 (light) to 900 (dark).</p>

<p>This is fine in its way, but the system may only become of interest to you when I tell you that you can make the tailwind utility classes responsive by simply adding a prefix to the style.</p>

<p>Tailwind recognizes the following screen-width "breakpoints":</p>

<div><table>
<thead>
<tr>
<th>Prefix</th>
<th>Screen Size</th>
<th>Minimum Width</th>
</tr>
</thead>
<tbody>
<tr>
<td>sm</td>
<td>Small devices</td>
<td>640px</td>
</tr>
<tr>
<td>md</td>
<td>Medium devices</td>
<td>768px</td>
</tr>
<tr>
<td>lg</td>
<td>Large devices</td>
<td>1024px</td>
</tr>
<tr>
<td>xl</td>
<td>Extra large devices</td>
<td>1280px</td>
</tr>
<tr>
<td>2xl</td>
<td>2x Extra large devices</td>
<td>1536px</td>
</tr>
</tbody>
</table></div>

<p>A style class such as "bg-gray-200" might thus be made to apply only to screens larger than 640px by specifying it as "sm:bg-gray-200".</p>

<p>The "This div has padding on all sides." example above could thus be made to display its paragraph with a blue background on screens with a maximum width of 640px and green on screens larger than this by styling it as follows:<br>
</p>

<pre class="brush:php;toolbar:false"><p>



<p>Because classes to the right take precedence, this makes the default background blue and overrides this with green when the screen is large enough. </p>

<p>For a fuller account of the Tailwind system and instructions on how to istall this in your project please see the Tailwind Website.</p>

<h3>
  
  
  3. Adaptive design for Server-side rendered webapps
</h3>

<p>Responsive design won't help you achieve more drastic effects where the desktop and mobile versions of a webapp are seriously different. Whereas a <strong>responsive design</strong> adjusts a standard pattern"fluidly" to accommodate different screen sizes, an <strong>adaptive</strong> design is prepared to give screen widths tailor-made solutions. </p>

<p>Expanding on the "tailoring" theme, you might think of responsive design as creating a single suit made of stretchable fabric that fits anyone. By contrast, adaptive design is like creating multiple tailored suits for different body types.</p>

<p>So if, for example, you felt that the mobile customers for your webapp were completely different from your desktop fans, you might want to give each community a tailor-made design (while delivering both under the same URL). </p>

<p>Conceptually, the obvious way to express this arrangement would be a displayIsMobile boolean guiding the display of MobileLayout and DesktopLayout components, as follows:<br>
</p>

<pre class="brush:php;toolbar:false">{#if displayIsMobile}
  <MobileLayout />
{:else}
  <DesktopLayout />
{/if}
登入後複製
登入後複製
登入後複製

但是您現在會問「這個 displayIsMobile 布林值如何初始化?」

當伺服器收到對myURL/myPage 的瀏覽器請求時,首先運行的通常是page.server.js 檔案中的load() 函數,執行伺服器端 來提供初始資料對於頁面。當 myPage 的 page.svelte - 也在伺服器端運行 - 接收到此資料時,它將想要執行其「模板」部分的初始渲染,並將 HTML 區塊發送回瀏覽器。但要做到這一點,它需要一個 displayIsMobile 的值。

如果您執行的是“客戶端”,那麼答案很簡單 - 使用“window”物件來檢查 window.width 並相應地設定 displayIsMobile。但在這種情況下,page.server.js 和 page.svelte 檔案(像它們一樣在伺服器端運行)都無法直接詢問客戶端。

一種選擇可能是為 displayIsMobile 選擇適當的預設值並傳回預設顯示。然後,您可以在用戶端上使用 onMount() 函數來檢查其視窗屬性並更適當地重新呈現預設顯示。然而,會產生兩個後果:

  • 當每個頁面啟動然後重新渲染時,初始顯示的重新渲染會在客戶端裝置上產生令人不快的「閃爍」效果。
  • SEO 可能會受到嚴重損害,因為網路爬蟲(可能不會總是執行 JavaScript)可能看不到正確的內容。

因此,如果您想正確處理此問題,您必須找到一種在伺服器上適當設定 displayisMobile 的方法。 這樣您就可以盡快向客戶端發送完全渲染的頁面,從而優化效能和 SEO。

如果您閱讀過 Post 3.5,您會記得伺服器請求附帶的「標頭」可用於傳輸有用的信息。瀏覽器請求頁面 myURL/myPage 的標頭可能包含任何有用的內容嗎?

值得慶幸的是,答案是「是的 - 他們確實如此」。例如,瀏覽器請求使用者代理程式標頭包含「引擎和瀏覽器」元件,該元件可用於告訴您請求來自行動瀏覽器而不是桌面瀏覽器。但用戶代理請求標頭的根源在於計算最黑暗的過去,其功能一直在努力平衡多種相互競爭的利益。

這裡的主要問題是對使用者環境的過於精確的描述(標題還包括使用者瀏覽器、作業系統類型和版本等的詳細資訊)可能會被用來在使用者導航時識別和追蹤使用者。網路。這個問題還沒解決。

這是一個「用戶代理」範例:

<h1>



<p>Previously in this series, you've seen styles applied to HTML elements like <p> by adding>

<p>The essence of Tailwind is that it provides a system of single-purpose "utility classes", each of which applies a specific set of styles to an element. The class names are chosen judiciously to provide a meaningful and practical expression of styling intentions. The example below styles a <p> element with 4rem padding on all four sides and a  background color of light gray.<br>
</p>

<pre class="brush:php;toolbar:false"><div>



<p>Here, in bg-blue-500, bg says that this is a background style, blue sets the background colour to blue and 500 sets the colour "intensity" to a mid-value on a scale of 100 (light) to 900 (dark).</p>

<p>This is fine in its way, but the system may only become of interest to you when I tell you that you can make the tailwind utility classes responsive by simply adding a prefix to the style.</p>

<p>Tailwind recognizes the following screen-width "breakpoints":</p>

<div><table>
<thead>
<tr>
<th>Prefix</th>
<th>Screen Size</th>
<th>Minimum Width</th>
</tr>
</thead>
<tbody>
<tr>
<td>sm</td>
<td>Small devices</td>
<td>640px</td>
</tr>
<tr>
<td>md</td>
<td>Medium devices</td>
<td>768px</td>
</tr>
<tr>
<td>lg</td>
<td>Large devices</td>
<td>1024px</td>
</tr>
<tr>
<td>xl</td>
<td>Extra large devices</td>
<td>1280px</td>
</tr>
<tr>
<td>2xl</td>
<td>2x Extra large devices</td>
<td>1536px</td>
</tr>
</tbody>
</table></div>

<p>A style class such as "bg-gray-200" might thus be made to apply only to screens larger than 640px by specifying it as "sm:bg-gray-200".</p>

<p>The "This div has padding on all sides." example above could thus be made to display its paragraph with a blue background on screens with a maximum width of 640px and green on screens larger than this by styling it as follows:<br>
</p>

<pre class="brush:php;toolbar:false"><p>



<p>Because classes to the right take precedence, this makes the default background blue and overrides this with green when the screen is large enough. </p>

<p>For a fuller account of the Tailwind system and instructions on how to istall this in your project please see the Tailwind Website.</p>

<h3>
  
  
  3. Adaptive design for Server-side rendered webapps
</h3>

<p>Responsive design won't help you achieve more drastic effects where the desktop and mobile versions of a webapp are seriously different. Whereas a <strong>responsive design</strong> adjusts a standard pattern"fluidly" to accommodate different screen sizes, an <strong>adaptive</strong> design is prepared to give screen widths tailor-made solutions. </p>

<p>Expanding on the "tailoring" theme, you might think of responsive design as creating a single suit made of stretchable fabric that fits anyone. By contrast, adaptive design is like creating multiple tailored suits for different body types.</p>

<p>So if, for example, you felt that the mobile customers for your webapp were completely different from your desktop fans, you might want to give each community a tailor-made design (while delivering both under the same URL). </p>

<p>Conceptually, the obvious way to express this arrangement would be a displayIsMobile boolean guiding the display of MobileLayout and DesktopLayout components, as follows:<br>
</p>

<pre class="brush:php;toolbar:false">{#if displayIsMobile}
  <MobileLayout />
{:else}
  <DesktopLayout />
{/if}
登入後複製
登入後複製
登入後複製

我認為很容易看出解析這個爛攤子時會遇到的問題!

但是還有其他選擇。 Google 最近的一項措施建議瀏覽器應該提供一個新的、更簡單的標頭,稱為 sec-ch-ua-mobile。它包含一個簡單的字串,告訴您瀏覽器是否期望移動響應(有關詳細信息,請參閱 Sec-CH-UA-Mobile)。

但是,雖然 Chrome 和 Edge 現在可以使用 sec-ch-ua-mobile 標頭,但其他瀏覽器不一定支援該計劃。無論如何,sec-ch-ua-mobile 標頭不會為您提供足夠的詳細資訊來完善您的回應並提供明確的「平板電腦」版本。

這一切都非常乏味,但可能足以讓您得出結論,您很樂意使用 sec-ch-ua-mobile 作為第一個停靠點,並使用 user-agent 作為後備。在這種情況下,這裡有一些程式碼可以為 page.svelte 檔案提供一個 displayIsMobile 變數。

令人困惑的是,它以一種名為 hooks.server.js 檔案的新型 Svelte 檔案開頭。

雖然您可能在 load() 函數中放置為 page.svelte 檔案設定 displayIsMobile 的程式碼,但並非每個 page.svelte 頁面都會具有其中之一。即使確實如此(當然,您總是可以建立一個),您也會發現必須在 all load() 函數中複製 displayIsMobile 程式碼。

相較之下,hooks.server.js 檔案是一種「超級」load() 函數,Svelte 會針對提交到伺服器的每個 請求啟動。它在執行任何其他活動之前運行。這使得它成為檢查 sec-ch-ua-mobile 標頭並為 displayIsMobile 建立值的完美位置。

下面的程式碼顯示如何透過 hooks.server.js 檔案建立 displayIsMobile。它還顯示如何將此值傳回預期的 page.svelte 檔案。

<h1>



<p>Previously in this series, you've seen styles applied to HTML elements like <p> by adding>

<p>The essence of Tailwind is that it provides a system of single-purpose "utility classes", each of which applies a specific set of styles to an element. The class names are chosen judiciously to provide a meaningful and practical expression of styling intentions. The example below styles a <p> element with 4rem padding on all four sides and a  background color of light gray.<br>
</p>

<pre class="brush:php;toolbar:false"><div>



<p>Here, in bg-blue-500, bg says that this is a background style, blue sets the background colour to blue and 500 sets the colour "intensity" to a mid-value on a scale of 100 (light) to 900 (dark).</p>

<p>This is fine in its way, but the system may only become of interest to you when I tell you that you can make the tailwind utility classes responsive by simply adding a prefix to the style.</p>

<p>Tailwind recognizes the following screen-width "breakpoints":</p>

<div><table>
<thead>
<tr>
<th>Prefix</th>
<th>Screen Size</th>
<th>Minimum Width</th>
</tr>
</thead>
<tbody>
<tr>
<td>sm</td>
<td>Small devices</td>
<td>640px</td>
</tr>
<tr>
<td>md</td>
<td>Medium devices</td>
<td>768px</td>
</tr>
<tr>
<td>lg</td>
<td>Large devices</td>
<td>1024px</td>
</tr>
<tr>
<td>xl</td>
<td>Extra large devices</td>
<td>1280px</td>
</tr>
<tr>
<td>2xl</td>
<td>2x Extra large devices</td>
<td>1536px</td>
</tr>
</tbody>
</table></div>

<p>A style class such as "bg-gray-200" might thus be made to apply only to screens larger than 640px by specifying it as "sm:bg-gray-200".</p>

<p>The "This div has padding on all sides." example above could thus be made to display its paragraph with a blue background on screens with a maximum width of 640px and green on screens larger than this by styling it as follows:<br>
</p>

<pre class="brush:php;toolbar:false"><p>



<p>Because classes to the right take precedence, this makes the default background blue and overrides this with green when the screen is large enough. </p>

<p>For a fuller account of the Tailwind system and instructions on how to istall this in your project please see the Tailwind Website.</p>

<h3>
  
  
  3. Adaptive design for Server-side rendered webapps
</h3>

<p>Responsive design won't help you achieve more drastic effects where the desktop and mobile versions of a webapp are seriously different. Whereas a <strong>responsive design</strong> adjusts a standard pattern"fluidly" to accommodate different screen sizes, an <strong>adaptive</strong> design is prepared to give screen widths tailor-made solutions. </p>

<p>Expanding on the "tailoring" theme, you might think of responsive design as creating a single suit made of stretchable fabric that fits anyone. By contrast, adaptive design is like creating multiple tailored suits for different body types.</p>

<p>So if, for example, you felt that the mobile customers for your webapp were completely different from your desktop fans, you might want to give each community a tailor-made design (while delivering both under the same URL). </p>

<p>Conceptually, the obvious way to express this arrangement would be a displayIsMobile boolean guiding the display of MobileLayout and DesktopLayout components, as follows:<br>
</p>

<pre class="brush:php;toolbar:false">{#if displayIsMobile}
  <MobileLayout />
{:else}
  <DesktopLayout />
{/if}
登入後複製
登入後複製
登入後複製

現在,displayIsMobile 位於瀏覽器請求的事件物件中。此事件是 SvelteKit 建構的一個複雜對象,用於表示目前請求。它包含以下屬性:

  • event.request:這是原始的 Request 對象,包含 HTTP 方法(GET、POST 等)、標頭、URL 和正文等詳細資訊。
  • event.locals:在請求的後續生命週期中提供此資料的位置。

正如您所想像的,由於 event 現在可以在任何需要它的地方使用,event.locals 正是您為 displayIsMobile 提供一個家所需要的。

handle() 的 {event, response} 參數的形式可能會讓您感到困惑。這是「解構」語法的範例。這使您能夠直接從物件中提取特定屬性,而無需引用物件本身。假設有一個超級物件 args,其中包含事件和回應作為屬性。然後而不是使用傳統的

User-Agent: Mozilla/4.9 Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
登入後複製

「解構語法」允許您將其寫為

// src/hooks.server.js
export async function handle({ event, resolve }) {

    let displayIsMobile;
    console.log("event.request.headers['sec-ch-ua-mobile']: ", event.request.headers.get('sec-ch-ua-mobile'));
    // First, try to get the mobile flag from the 'sec-ch-ua-mobile' header. This is a string header
    // and its value is '?1' if the user agent is a mobile device, otherwise it is '?0'.
    if (event.request.headers.get('sec-ch-ua-mobile') !== undefined) {
        displayIsMobile = event.request.headers.get('sec-ch-ua-mobile') === '?1' ? true : false;
    } else {
        // Otherwise, try the 'user-agent' header. For robust mobile detection, you might consider using
        // the ua-parser-js library. It provides consistent results across various edge cases.
        if (event.request.headers.get('user-agent') !== undefined) {
            displayIsMobile = event.request.headers.get('user-agent').toLowerCase().includes('mobile');
        } else {
            displayIsMobile = false
        }
    }

    // Put displayIsMobile into event.locals. This is an object provided by SvelteKit that is specific to a
    // particular browser request and which is acessible in every page and layout. In brief, event.locals lets
    // you pass data throughout the lifecycle of a request in SvelteKit. It provides a convenient way to share
    // computed values or state without needing to repeat logic or fetch data multiple times.
    event.locals.displayIsMobile = displayIsMobile;

    // Proceed with the request. In SvelteKit, resolve(event) is crucial for handling the request lifecycle.
    // It processes the current request and generates the final response that will be sent back to the client.
    const response = await resolve(event);
    return response;
}
登入後複製

本質上,這是一種在不知道父物件名稱(args)的情況下引用物件 args 的屬性(args.event 等)的方法。這會導致程式碼更緊湊、更有彈性。

無論如何,儘管如此,由於displayIsMobile 現在位於瀏覽器請求的事件物件中,顯然要做的事情就是在page.server.js 檔案中使用load() 函數將其挖掘出來並返回它到page. svelte。

function handle(args) {
    const event = args.event;
    const resolve = args.resolve;
    // ... (code referencing variables "event" and "resolve")
}
登入後複製

最後,這是一個非常簡單的 page.svelte 文件,用於提供自適應頁面

function handle({ event, resolve }) {
    // ...(code referencing variables "event" and "resolve")
}
登入後複製

希望您喜歡!

總而言之,完整的順序是:

  1. Sveltekit 伺服器處理瀏覽器的 myURL/myPage 請求並啟動專案的 hooks.server.js 檔案。在這裡,檢索請求標頭,確定適當的 displayIsMobile 值,並將結果隱藏在 Sveltekit 事件物件中。
  2. myPage 路由的 page.server.j 檔案中的 load() 函數從事件中擷取 displayIsMobile 並將其傳回給 page.svelte
  3. page.svelte 檔案檢索 data.displayIsMobile 值並在其範本部分中使用該值來產生適當的 HTML。
  4. Sveltekit 為瀏覽器建立腳本來新增互動行為。 Tailwind 引用在頁面建置期間已轉換為 CSS 媒體查詢。
  5. 瀏覽器接收此 HTML,使用 Sveltekit 腳本「水合」它,並根據媒體查詢的指示將其呈現在用戶端裝置上。

頁面水合後,反應性就純粹是客戶端關心的問題了。 程式碼範本部分中的 SvelteKit {#if popupIsVisible 將成為一個編譯函數,根據 popupIsVisible 切換 DOM 元素。

以上是NgSysV.響應式/自適應設計的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板