使用JavaScript更改背景图像

时间:2012-05-07 00:25:12

标签: javascript jquery html css

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

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');
});

2 个答案:

答案 0 :(得分:3)

如果尝试直接在函数中说出background-size怎么办?

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

因为我认为当背景发生变化时,previouse background-size属性可能无法用于新图像......

答案 1 :(得分:2)

试试这个,它对我有用。

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是我用来改变背景图像的按钮。