How can I change the background image with a link

2019-09-02 12:57发布

I've tried searching for this in the forums but all the results are always something to do with div tags or things like that. Nothing seems relevant to my own issue.

What I was is simply to change the background image of my page to a new image upon clicking a link.

The current css to the background image is as follows...

body { 
    background:#000000 url(../img/wood01.jpg) no-repeat fixed center center; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

And I just want to use links that currently formatted for lists...

<li>
    <font color="#FFFFFF">Change Background</font> 
        <ul class="dropup">
            <li><a href="#" id="bgimg01">Link 1</a></li>
            <li><a href="#" id="bgimg02">Link 2</a></li>
            <li><a href="#" id="bgimg03">Link 3</a></li>
        </ul>
</li>

And I don't want the page to refresh when the link is clicked. I need the background to change dynamically.

2条回答
别忘想泡老子
2楼-- · 2019-09-02 13:34

A js solution is,

http://jsfiddle.net/NmFru/

HTML

<li>
    <font color="#FFFFFF">Change Background</font> 
        <ul class="dropup">
            <li><a href="#" id="140x101" onclick="changeImage(this.id)">Link 1</a></li>
            <li><a href="#" id="140x102" onclick="changeImage(this.id)">Link 2</a></li>
            <li><a href="#" id="140x103" onclick="changeImage(this.id)">Link 3</a></li>
        </ul>
</li>

JS

function changeImage(img){

    document.body.style.backgroundImage = 'url(http://placehold.it/'+img+')';

}
查看更多
Deceive 欺骗
3楼-- · 2019-09-02 13:40

Use some jQuery:

$('#bgimg01').on('click', function() {
    $('body').css('background-image', 'url(http://placehold.it/200x200/ff0000)');
})
$('#bgimg02').on('click', function() {
    $('body').css('background-image', 'url(http://placehold.it/200x200/hh3476)');
})
$('#bgimg03').on('click', function() {
    $('body').css('background-image', 'url(http://placehold.it/200x200/gg0000)');
})

DEMO: http://jsfiddle.net/LPUgF/158/

查看更多
登录 后发表回答