使用JavaScript更改背景图像

问题描述:

我有一个背景图像被拉伸以适应整个屏幕。我正在尝试编写一个将背景更改为另一个图像的脚本。我当前的脚本不会将图像拉伸以适应整个屏幕,而是将图像居中。在Firefox,IE和Opera中会出现此问题。 Chrome和Safari似乎未受影响。我跟着this教程来创建整页背景图片。使用JavaScript更改背景图像

CSS:

html { 
    background: url(../img/01.jpg) no-repeat center fixed; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
} 

的JavaScript:

$('#previous').click(function() { 
    $('html').css('background', 'url(img/01.jpg) no-repeat center fixed'); 
}); 

$('#next').click(function() { 
    $('html').css('background', 'url(img/02.jpg) no-repeat center fixed'); 
}); 
+0

不知道这是否会有所帮助,但是您是否曾尝试将html标签的高度和宽度设置为100%? – Chase

+0

刚刚尝试过,但没有工作:( – Jon

如果尝试直接在功能上说背景大小?

$('#next').click(function() { 
    $('html').css('background', 'url(img/02.jpg) no-repeat center fixed'); 
    $('html').css('background-size', 'cover'); 
}); 

因为我想,当背景的变化,previouse背景-size属性可能是不工作的新形象......

+0

美丽,工作。谢谢:) – Jon

试试这个,它为我工作。

CSS
body { 
    background-image: url('img/bg2.jpg'); 
    color: #000305; 
    font-size: 87.5%; /* Base font size: 14px */ 
    font-family: 'Trebuchet MS', Trebuchet, 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; 
    line-height: 1.429; 
    margin: 0; 
    padding: 0; 
    text-align: left; 
    } 

.body { 
    clear: both; 
    margin: 0 auto; 
    width: 70%; 
} 

而在HTML中我用下面的脚本

$(document).ready(function() { 

$("#tb").click(function() { 
var body = document.getElementsByTagName('body')[0]; 
body.style.backgroundImage = 'url(img/p2.jpg)'; 

    }); 

}); 

其中TB是我用来更改背景图片的按钮。