如何在SASS中建立佔位符mixin


概述

佔位符是HTML輸入標籤的一個屬性,它告訴使用者該輸入標籤需要填寫什麼資訊。要設定輸入標籤的佔位符樣式,我們將使用**語法高效樣式表(SASS)**預處理器指令碼語言,它提供了一個mixin的功能。mixin就像我們在其他程式語言中建立的簡單函式一樣。它可以幫助我們避免在樣式表中重複樣式。要在我們的程式中使用SASS mixin,首先必須將SASS安裝到我們的桌面環境中,這將使我們的程式碼能夠使用mixin。

語法

在sass中建立mixin的語法如下:

@mixin functionName(arguments…) {
   Styling her....
}
  • 函式名 - 函式名可以是任何使用者定義的名稱,用於定義樣式程式碼塊

  • 引數 - 引數用於動態地將值作為變數傳遞給函式,這將用於元素的樣式屬性。

演算法

步驟1 - 在你的文字編輯器中建立一個HTML基本結構。

步驟2 - 建立一個父div容器,其中包含所有輸入欄位。

<div style="display: flex;flex-direction: column;width: 20rem;margin: auto;"></div>

步驟3 - 在父容器內建立一個HTML輸入欄位。

<input type="text">

步驟4 - 向input標籤新增placeholder屬性,併為其提供一個值。

<input type="text" placeholder="Full Name">

步驟5 - 如果你想新增更多輸入欄位,請重複步驟3和4。

步驟6 - 現在在與style.scss相同的資料夾中建立一個新檔案,使用@mixin建立mixin,後跟函式名。

@mixin placeholderFunction($placecolor) {
}

步驟7 - 選擇placeholder偽選擇器,並使用css樣式屬性對其進行樣式設定。

&::placeholder {
   color: $placecolor;
}
&::-webkit-input-placeholder{
   color: $placecolor;
}

步驟8 - 現在在mixin外部選擇輸入欄位,並使用@include指令在輸入欄位內呼叫mixin,並將顏色名稱傳遞進去。

input[type="text"]{
   @include placeholderFunction(green);
   font-weight: 700;
   margin: 0.2rem 0;
   font-style: italic;
   padding: 0.4rem;
}

步驟9 - 現在使用以下命令編譯SCSS檔案。

sass style.scss > style.css

步驟10 - 現在將style.css連結到index.html程式碼的head標籤中。

<link rel="stylesheet" type="text/css" href="style.css">

步驟11 - 在瀏覽器中開啟程式碼,佔位符樣式更改將被反映。

示例

在給定的示例中,我們建立了一些輸入欄位,這些欄位包含具有特定值的placeholder屬性。

<html>
<head>
<title>Mixin Placeholder</title>
   <link rel="stylesheet" type="text/css" href="style.css">
   <style>
      @mixin placeholderFunction($placecolor) {
         &::placeholder {
            color: $placecolor;
         }
         &::-webkit-input-placeholder{
            color: $placecolor;
         }
      }
      input[type="text"]{
      @include placeholderFunction(green);
         font-weight: 700;
         margin: 0.2rem 0;
         font-style: italic;
         padding: 0.4rem;
      }
      style.css
      input[type=text] {
         font-weight: 700;
         margin: 0.2rem 0;
         font-style: italic;
         padding: 0.4rem;
      }
      input[type=text]::placeholder {
         color: green;
      }
      input[type=text]::-webkit-input-placeholder {
         color: green;
      }
   </style>   
</head>
<body>
   <div style="display: flex;flex-direction: column;width: 20rem;margin: auto;">
      <h2>SASS Mixin For Placeholder</h2>
      <input type="text" placeholder="Full Name">
      <input type="text" placeholder="Email">
      <input type="text" placeholder="Password">
      <input type="text" placeholder="Confirm Password">
   </div>
</body>
</html>

下圖顯示了上面index.html、style.scss和style.css程式碼的輸出。下圖顯示了四個輸入欄位,其佔位符為全名、電子郵件、密碼、確認密碼,所有這些佔位符都是使用sass mixin設定樣式的。

結論

我們可以看到,sass mixin使開發人員不必多次編寫相同的程式碼,並且使用sass我們可以建立一個變數,這對於更改佔位符來說是很好的。因此,如果我們想更改輸入欄位的佔位符顏色,我們只需要更改單個變數,而無需更改整個樣式表。

更新於:2023年4月11日

瀏覽量:159

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.