1. 程式人生 > >JavaScript設定背景圖片

JavaScript設定背景圖片

本章節通過程式碼例項介紹一下如何利用js實現動態的為div元素設定背景圖片。

核心程式碼片段如下:

[JavaScript] 純文字檢視 複製程式碼執行程式碼
1odiv.style.backgroundImage="url('images/test.jpg')";

下面給出一個完整的程式碼例項,使用的背景圖片如下:

a:3:{s:3:\"pic\";s:43:\"portal/201711/25/204505z898abioy7warmjt.png\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

309x99的圖片分隔為9份,每一份的長寬分別是103px和33px。

程式碼例項如下:

010203040506070809101112131415161718192021222324252627282930<!doctype html><html><head>
<meta charset="utf-8"><title>設定背景圖片</title><style type="text/css">#ant {width:400px;height:300px;background-color:#ccc;}</style><script>window.onload = function () {var odiv = document.getElementById("ant");var obt = document.getElementById("bt");obt.onclick = function () {
odiv.style.backgroundImage = "url('mytest/demo/mybg.png')";odiv.style.backgroundRepeat = "no-repeat";odiv.style.backgroundPosition = "0px -33px";}}</script></head><body><div id="ant"></div><input type="button" id="bt" value="檢視演示"/></body></html>

上面的程式碼實現了使用js設定元素背景的功能,可以看出背景圖片會覆蓋背景色。

(1).backgroundImage用來設定背景圖片路徑。

(2).backgroundRepeat用來設定背景圖片的重複規則。

(3).backgroundPosition用來設定背景圖片的定位。

也可以使用setAttribute()函式實現