2012-10-26 82 views
0

如何用jQuery或java腳本更改onClick背景圖片?我點擊「>」(下一個箭頭),當點擊「<」(後退箭頭)時切換到上一個背景圖像,我想要改變爲下一個背景圖像。 。用jQuery和html5點擊更改背景圖片

我正在用響應html5和css3開發這個網站。

<script type="text/javascript" src="jquery-1.8.2.min.js"></script> //jquery inside the folder ok 
<script type="text/javascript">           
var images = ['url("../images/1366x768/image-_0107.jpg")', 'url("../images/1366x768/image-_0012.jpg")'], curIndex = 0; // here I set the images inside the desired folder 

// Left arrow selector 
$('.backarrow').click(function() { //here I set the back arrow "<" 
    if (curIndex > 0) { 
     // Container selector 
     $('backgrounds').css('../images/1366x768/image-0061.jpg', images[--curIndex]); // here I set my file backgrounds.css and the default image configured there 
    } 
}); 

// Right arrow selector 
$('.nextarrow').click(function() { 
    if (curIndex < images.length - 1) { 
     // Container selector 
     $('backgrounds').css('../images/1366x768/image-0061.jpg', images[++curIndex]); 
    } 
}); 
</script> 

<!--HTML 5 --> 

<div id="square"><a href="" class="nextarrow">></a> <!-- here I call my jquery --> 
</div> 
<div id="square"><a href="" class="backarrow"><</a> <!-- here I call my jquery --> 
</div> 

/* CSS3 */ 

/* backgrounds.css */ 

body { 
    background: #dcd8d5 url(../images/1366x768/image-_0061.jpg) no-repeat center center fixed; -webkit-background-size: cover; 
-moz-background-size: cover; -o-background-size: cover; background-size: cover } 

/* default.css */ 

.nextarrow { 
    font-size:20px; color:#666; font-style:normal 
} 
.backarrow { 
    font-size:20px; color:#666; font-style:normal 
} 

我做錯了什麼?

回答

0

這樣做的jQuery的方法是如下:

$("#background").css("background-image","url(img_url_here)"); 

我不是很確定你想選擇所以我做了一個的jsfiddle希望這將使它更容易爲你找出:

JSFiddle

+0

是的,謝謝,幾乎是這樣,我需要這個腳本選擇一個數組中的圖像,所以當我點擊下一個>>'去數組中的下一個圖像,當我點擊'上一個<<' – user1777158

+0

數組中有什麼,所有圖像的id或bg圖像的來源? –

+0

Lenny,請檢查我的JSFiddle http://jsfiddle.net/mNQ3R/提前致謝! – user1777158

0

的錯誤似乎是在這一行:

$('backgrounds') 

你到底是想用這個選擇是什麼?如果是id =「backgrounds」的對象,你應該使用$('#backgrounds'),如果它是一個類,你可以使用$('。backgrounds')來選擇它。您使用的方式,jQuery正在嘗試搜索名爲「backgrounds」的元素(即標籤)。 (我敢肯定,是不是你正在嘗試做的)

任何方式,如果你想改變的背景圖像,讓我們說,你的身體元素,你應該使用類似:

$(document).ready(function() { 
    $(".nextarrow").click(function(){ 
    { 
     $('body').css("background-image","url(../images/1366x768/image-0061.jpg)"); // Correct the path to your image 
    } 

} 

或者,您可以將背景圖片從ID恰好是「背景」使用元素改變:

$('#backgrounds').css("background-image","url(../images/1366x768/image-0061.jpg)"); // Correct the path relative to the html document this script is running. 

我希望它幫助。乾杯

+0

沒有發生....我試圖改變背景圖像當我點擊「>」符號,並返回到之前的圖像時,我點擊符號「<」 這是原來的例子....但我無法做到這一點! http://stackoverflow.com/questions/13087684/change-background-image-onclick – user1777158

+0

張貼您的HTML。 –

+0

請參閱我對$(document).ready部分的編輯 –