这是当前的背景:
html {
background: url('source.gif') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 100%;
}
然后我用它改变它(当悬停在按钮上时):
document.getElementById('b1').addEventListener('mouseover', () => {
document.body.style.backgroundImage = "url('src2.gif')";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
});
但问题是它甚至不是全屏。
我希望它具有前一个具有的所有相同属性(我的意思是在CSS中)。
我该怎么做?
答案 0 :(得分:1)
更改css以使其适用于body元素,而不是html
document.getElementById('b1').addEventListener('mouseover', () => {
document.body.style.backgroundImage = "url('https://cdn.pixabay.com/photo/2017/07/24/19/57/tiger-2535888_960_720.jpg')";
});

body, html {
height: 100%;
padding:0;
margin:0;
}
html {
background: url('https://cdn.pixabay.com/photo/2016/05/27/18/31/chaffinch-1420407_960_720.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

<button id="b1" value="b1">Other Image</button>
&#13;
答案 1 :(得分:1)
您应该更改相同的元素,当初始css设置适用于body
时,您会更改html
个样式。
这是小提琴: https://jsfiddle.net/c59eymf8/1/
JS:
document.getElementById('b1').addEventListener('mouseover', function () {
document.body.style.backgroundImage = "url('https://wow.olympus.eu/webfile/img/1632/x=1024/oly_testwow_stage.jpg')";
document.body.style.backgroundRepeat = "no-repeat";
});
CSS:
body {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/PM5544_with_non-PAL_signals.png/384px-PM5544_with_non-PAL_signals.png') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
min-height: 100%;
}
答案 2 :(得分:0)
在css中你有<html>
的样式,但在javascript中你改变了体型。
body {
background: url('source.gif') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 100%;
}
document.getElementById('b1').addEventListener('mouseover', () => {
document.body.style.backgroundImage = "url('src2.gif')";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
});
此外,如果您想在鼠标未超过b1
元素后返回第一个值,则应添加以下内容:
document.getElementById('b1').addEventListener('mouseleave', () => {
document.body.style.backgroundImage = "url('source.gif')";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
});
还行
document.body.style.backgroundSize = "cover";
是多余的,因为此属性在css中设置为alredy。