2012-10-26 78 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部分的编辑 –