2013-02-25 113 views
0

雖然我可以看到這個問題已經被問到,我真的需要一個解決方案,而不使用JQuery,它的嵌入式Web界面,我不想加載jQuery的開銷。我需要能夠使用單個頁面上的JS來操作精靈,精靈的狀態依賴於某些JS變量。我相信這一定是可能的,但如果不使用JQuery就不能找到任何東西。用Javascript更改背景位置?

+0

你嘗試過這麼遠嗎?我會使用不同的類名並使用JavaScript更改這些類。 – 2013-02-25 12:00:47

+0

給我們你的HTML http://jsfiddle.net/ – 2013-02-25 12:02:08

+0

http://javascript.gakaa.com/style-backgroundposition.aspx – Ziinloader 2013-02-25 12:03:56

回答

3

最簡單的方法(我認爲)是定義自己的CSS類和改變事件色丹那些clasess。即

<style type="text/css"> 
.bg1{ 
/* Some attributes set here */ 
background-position:cen‌​ter; 
} 
.bg2{ 
/* Some attributes set here */ 
background-position:left; 
} 

</style> 

,然後你把你的JavaScript這樣

document.getElementById("some_id").class = "bg2"; 
+0

感謝這基本上是我使用的解決方案,除了我使用的函數:document.getElementById(「some_id」).className作爲.class似乎沒有工作? – Matt104 2013-02-25 16:58:55

1

我認爲你可以使用Object.style.backgroundPosition =「position」來改變你想要的背景位置。

試試這個代碼

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div 
{ 
background-image: url('example.png'); 
background-repeat: no-repeat; 
width: 400px; 
height: 400px; 
border: 1px solid #000000; 
} 
</style> 
<script> 
function displayResult() 
{ 
document.getElementById("div1").style.backgroundPosition="center bottom"; 
} 
</script> 
</head> 
<body> 

<button type="button" onclick="displayResult()">Position background image</button> 
<br> 
<div id="div1"> 
</div> 

</body> 
</html> 

Reference

+0

Firefox 26不會對backgroundPosition更改作出反應。在CSS中定義時.styyle.backgroundPosition未定義。它沒有記錄在MDN上。 – Dereckson 2014-02-09 13:13:52