How can I change the background image with a link

血红的双手。 提交于 2020-01-06 15:02:46

问题


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.


回答1:


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

}



回答2:


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/



来源:https://stackoverflow.com/questions/19770154/how-can-i-change-the-background-image-with-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!