如何在JavaScript中設定文字中單詞之間的間距?


在本文中,我們將學習如何在JavaScript中設定文字中單詞之間的間距。

單詞間距在網站上至關重要,因為它可以提高頁面上顯示文字的可讀性和易讀性。您可以使用合適的單詞間距來生成美觀易讀的字型。

JavaScript中,我們使用`wordSpacing`屬性來設定網站上顯示文字中單詞之間的間距。

使用Style wordSpacing屬性

JavaScript DOM屬性用於獲取和設定文字中單詞之間的間距。

根據您的需要,您可以將`wordSpacing`屬性的值設定為正值或負值。例如,根據您的需要,您可以將單詞之間的間距設定為50畫素或-50畫素。

與Web瀏覽器的相容性

此JavaScript屬性與包括Google Chrome、Safari、Internet Explorer、Opera、Chromium和Mozilla Firefox在內的瀏覽器相容。

語法

要在文字中實現此JavaScript屬性,您應該遵循以下語法:

object.style.wordSpacing = "normal | length | initial | inherit"

引數

  • normal - 這是單詞之間間距的預設值。使用時,它將返回正常間距的單詞。
  • length - 指定單詞之間的空格。長度值可以是正值或負值。
  • initial - 此值將屬性設定為其預設值。
  • inherit - 此值用於從其父元素繼承屬性。

示例

在此示例中,我們將使用`wordSpacing`屬性來設定單詞之間的間距。我們將把單詞間距設定為50畫素。

<html> <head> <style> #myText { font-family: sans-serif; font-weight: normal; font-size: 18px; } </style> </head> <body> <h3> Setting the Spacing between words in a text in JavaScript using <i> wordSpacing </i> Property </h3> <p id="myText"> Some placeholder material for this multi-collapse example's initial collapse component. </p> <script> var output = document.getElementById("myText").style.wordSpacing="50px"; </script> </body> </html>

示例2

在此示例中,我們將單詞間距的長度設定為負值。我們將值設定為-30畫素。

<html> <head> <style> #myText { font-family: sans-serif; font-weight: normal; font-size: 18px; } </style> </head> <body> <h3> Setting the Spacing between words in a text in JavaScript using <i> wordSpacing </i> Property </h3> <p id="myText"> Some placeholder material for this multi-collapse example's initial collapse component. </p> <script> var output=document.getElementById("myText").style.wordSpacing="-30px"; </script> </body> </html>

示例3

在此示例中,我們將單詞間距值設定為normal。

<html> <head> <style> #myText { font-family: sans-serif; font-weight: normal; font-size: 18px; } </style> </head> <body> <h3> Setting the Spacing between words in a text in JavaScript using <i> wordSpacing </i> Property </h3> <p id="myText"> Some placeholder material for this multi-collapse example's initial collapse component. </p> <script> var output=document.getElementById("myText").style.wordSpacing=normal; </script> </body> </html>

本文教我們如何使用JavaScript的`wordSpacing`屬性來設定文字中單詞之間的間距。使用此屬性,您可以為單詞間距的長度指定負值、正值或normal值。

更新於:2022年11月22日

4K+ 次檢視

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告