如何创建一个按钮,将整个网站的背景图像更改为随机图像?
<script>
function randomHero() {
var heroPics = ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/musician-background-1680.jpg','https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/pink-floyd-division-bell-228953.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/northstar.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/womensrights.jpg'];
$('body').css({
'background' : 'url('+ heroPics[Math.floor(Math.random() * heroPics.length)] + ') no-repeat',
'background-attachment' : 'scroll',
'background-position' : '50% 50%',
'background-size' : 'cover'
});
}
randomHero();
$('button').on('click', randomHero);
</script>
答案 0 :(得分:2)
不要忘记包含jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function randomHero() {
var heroPics = ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/musician-background-1680.jpg','https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/pink-floyd-division-bell-228953.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/northstar.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/womensrights.jpg'];
$('body').css({
'background' : 'url('+ heroPics[Math.floor(Math.random() * heroPics.length)] + ') no-repeat',
'background-attachment' : 'scroll',
'background-position' : '50% 50%',
'background-size' : 'cover'
});
}
randomHero();
$('button').on('click', randomHero);
</script>
答案 1 :(得分:2)
确保包含jQuery和按钮。
function randomHero() {
var heroPics = ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/musician-background-1680.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/pink-floyd-division-bell-228953.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/northstar.jpg', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/392/womensrights.jpg'];
$('body').css({
'background': 'url(' + heroPics[Math.floor(Math.random() * heroPics.length)] + ') no-repeat',
'background-attachment': 'scroll',
'background-position': '50% 50%',
'background-size': 'cover'
});
}
randomHero();
$('button').on('click', randomHero);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton">Change Background</button>