如何使用JavaScript設定背景影像的定位區域?
在本教程中,我們將學習如何使用JavaScript設定背景影像的定位區域。
可以使用HTML DOM Style `background-origin` 屬性更改程式中背景影像的定位區域。
`background-origin`是一個允許您修改網頁背景影像的特性。此屬性用於設定背景圖片的原點。預設情況下,背景影像原點設定為螢幕/網頁的左上角。
`background-origin` 屬性指定背景的原點:從邊框開始、邊框內或填充內。當 `background-attachment` 值設定為“fixed”時,此屬性將不起作用。`background-origin` 屬性與 `background-clip` 屬性相同,只是它不是裁剪背景,而是調整背景大小。螢幕的左上角是元素的預設原點。
如果元素包含多個背景圖片,我們可以使用逗號分隔每個背景影像的`background-origin`屬性值。每個圖片都將對應於`background-origin`屬性的值。
以下是使用JavaScript設定背景影像定位區域的方法。
使用 `backgroundOrigin` 的 `content-box` 屬性
`backgroundOrigin` 屬性提供背景圖片的位置,並且使用 `content-box` 屬性,背景相對於內容框定位。背景從內容的左上角開始。`content-box` 屬性覆蓋放置在框內的內容。
填充框是預設值,它將背景相對於框定位。填充邊緣的左上角作為背景的起點。
語法
document.getElementById("box").style.backgroundOrigin = "content-box";
使用 `getElementbyId()` 方法獲取框,並將框的背景原點指定為 `content-box` 屬性。
示例
在這個示例中,我們使用邊框、填充、寬度、高度和背景顏色等引數建立了一個框。框內包含一些文字形式的內容。
該框容納一個圖片,其定位區域被指定為其預設值——填充框。此屬性更改為 `background-origin` 屬性的 `content-box` 屬性。此影像放置在框的填充區域中,並移至包含文字的區域。
<html> <head> <style> #box { border: 3px dashed red; padding: 35px; width: 500px; height: 260px; background: url('https://tutorialspoint.tw/videotutorials/images/coding_ground_home.jpg') no-repeat; background-color: yellow; background-origin: padding-box; } </style> </head> <body> <h3> Set the positioning area of the background image using <i> content-box property </i> </h3> <button onclick="myFunction()"> Set area of background image</button> <div id="box"> This is demo text. </div> <script> function myFunction() { document.getElementById("box").style.backgroundOrigin="content-box"; } </script> </body> </html>
使用 `backgroundOrigin` 的 `padding-box` 屬性
`backgroundOrigin` 屬性指示背景的定位區域,即由 `background-image` 屬性提供的影像原點的位置。
`padding-box` 屬性指定背景延伸到填充的外邊緣。在邊框下方不繪製背景。這是預設選項。`border-box` 屬性指定背景延伸到邊框外邊緣。背景繪製在邊框下方。
此 `background-origin` 屬性的初始值設定為其預設值。“inherit”屬性指定相關元素繼承其父元素的 `background-origin` 屬性。
語法
document.getElementById("box").style.backgroundOrigin = "padding-box";
使用 `getElementbyId()` 方法獲取框,`padding-box` 屬性提供框的 `background-origin`。
示例
在這個示例中,我們構建了一個包含邊框、填充、寬度、高度和背景顏色的框。框內有一些文字形式的資料。該框包含一個影像,其放置區域被指定為 `border-box` 屬性。此屬性修改為 `background-origin` 屬性的 `padding-box` 屬性。此影像的放置方式使其覆蓋了框的邊框。但是,應用 `padding-box` 屬性後,影像被重新定位到包含框填充的區域,省略了邊框。
<html> <head> <style> #box { border: 3px dashed red; padding: 35px; width: 500px; height: 260px; background: url('https://tutorialspoint.tw/videotutorials/images/coding_ground_home.jpg') no-repeat; background-color: yellow; background-origin: border-box; } </style> </head> <body> <h3> Set the positioning area of the background image using <i> padding-box property </i> </h3> <button onclick="myFunction()"> Set area of background image</button> <div id="box"> This is a demo text. </div> <script> function myFunction() { document.getElementById("box").style.backgroundOrigin="padding-box"; } </script> </body> </html>
在本教程中,我們學習瞭如何使用 `background-origin content-box` 屬性和 `backgroundorigin padding-box` 屬性使用 JavaScript 設定背景影像的定位區域。