繁体   English   中英

使用jquery和html5单击更改背景图像

[英]change background image on click with jquery and html5

如何使用jquery或java脚本更改背景图片onClick?

例如:我有六(6)张图像,我想在单击“>”(下一个箭头)时更改为下一个背景图像,并在单击“ <”(后退箭头)时更改为上一个背景图像。

我正在使用响应式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 
}

我在做什么错?

错误似乎在这一行:

$('backgrounds')

您到底要尝试选择什么? 如果是id =“ backgrounds”的对象,则应使用$('#backgrounds'),如果它是一个类,则可以使用$('。backgrounds')选择它。 jQuery使用的方式是尝试搜索名为“ backgrounds”的元素(即标签)。 (我很确定这不是您要尝试的操作)

无论如何,如果要更改背景图像(例如,您的body元素),则应使用类似以下内容的方法:

$(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.

希望对您有所帮助。 干杯

jQuery的方法如下:

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

我不确定您要选择什么,所以我做了一个jsfiddle,希望可以使您更容易发现:

JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM