如何用 JavaScript DOM 將背景影像設定為固定影像?


要透過 JavaScript 固定背景影像,請使用backgroundAttachment屬性。該屬性允許您設定不會滾動的影像。

示例

您可以嘗試執行以下程式碼來了解如何使用 JavaScript 中的backgroundAttachment屬性 -

動態演示

<!DOCTYPE html>
<html>
   <body>
      <button onclick="display()">Click to Set background</button>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <p>Demo Text</p>
      <script>
         function display() {
            document.body.style.background = "url('https://tutorialspoint.tw/html5/images/html5-mini-logo.jpg') no-repeat right top";
            document.body.style.backgroundAttachment = "fixed";
         }
      </script>
   </body>
</html>

更新於: 2020 年 6 月 23 日

510 次瀏覽

開始您的 職業生涯

完成課程並獲得認證

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