document.body.style.backgroundImage不起作用

时间:2014-09-10 17:20:50

标签: javascript css

我对document.body.style.backgroundImage标记有疑问。 它在本地完美,但不在服务器上。

<a href="roztoky.php" onclick = "document.body.style.backgroundImage = 'url(../img/roztoky.png)';">

在本地,背景切换没有任何问题,但在服务器上,背景只出现了几秒钟,然后它被淹没回到defalut

但如果我这样称呼它:

<a href="_section/roztoky.php" onclick = "document.getElementById('frame').style.backgroundImage = 'url(img/roztoky.png)';" target="a">

它有效......

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用jquery

DEMO:

更改

<a id="a" href="roztoky.php" onclick = "document.body.style.backgroundImage = 'url(../img/roztoky.png)';">

$('#a').on('click', function() {
    $('body').css('background-image', 'url(/img/roztoky.png)');
});

<a id="b" href="_section/roztoky.php" onclick = "document.getElementById('frame').style.backgroundImage = 'url(img/roztoky.png)';" target="a">

$('#b').on('click', function() {
    $('#frame').css('background-image', 'url(img/roztoky.png)');
});

或使用纯javascript

DEMO

    var button_a = document.querySelector("#a"),
    button_b = document.querySelector("#b"),
    myframe  = document.querySelector("#frame");
button_a.addEventListener("click",function(e){
    document.body.style["background-image"] = "url(https://c2.staticflickr.com/6/5530/11442019345_d50b753156.jpg)";
},false);
button_b.addEventListener("click",function(e){
    myframe.style.style["background-image"] = "url(https://c2.staticflickr.com/4/3702/11442187163_fdd370b657_n.jpg)";
},false);

HTML ::

<a id="a">body background image</a>
<a id="b">change frame background</a>
<div id="frame"></div>

CSS ::

#frame{
    width:100%;
    height:320px;
}

a{
    padding: 6px 12px;
    background:#ccc;
    border-radius:6px;
    cursor:pointer;
    color:white;
}