简体   繁体   中英

JS change background image (of page not element) on mouseover

I want to find out how load a different background image for the whole page when you mouseover the links. The fullscale background image uses the js script called Fullscreenr.

The background image for this page is given an id

Any ideas? I don't even know how to to search for the correct terms here.

http://www.rollinleonard.com/projects/

Since you have jQuery loaded on the page, but it's not mentioned in the question, I'll offer a jQuery and an non-jQuery solution.

jQuery:

<script type="text/javascript">
    $(function() {
        var bgimg = $('#bgimg');

        var images = [
            '/src/of/img1.jpg',
            '/src/of/img2.jpg',
            '/src/of/img3.jpg',
            '/src/of/img4.jpg',
            '/src/of/img5.jpg',
            '/src/of/img6.jpg',
            '/src/of/img7.jpg',
            '/src/of/img8.jpg',
            '/src/of/img9.jpg',
            '/src/of/img10.jpg'
        ];

        $('p.overlayimage > a').each(function( i ) {
            $(this).mouseenter(function() {
                bgimg.attr( 'src', images[ i ] );
            });
        });
    });
</script>

If you're not going to use jQuery, then do change:

<p class="overlayimage">

to:

<p id="overlayimage">

and do this:

<script type="text/javascript">
    var bgimg = document.getElementById('bgimg');

    var images = [
        '/src/of/img1.jpg',
        '/src/of/img2.jpg',
        '/src/of/img3.jpg',
        '/src/of/img4.jpg',
        '/src/of/img5.jpg',
        '/src/of/img6.jpg',
        '/src/of/img7.jpg',
        '/src/of/img8.jpg',
        '/src/of/img9.jpg',
        '/src/of/img10.jpg'
    ];

    var aElems = document.getElementById('overlayimage').getElementsByTagName('a'),
        len = aElems.length;

    function generateHandler( i ) {
        return function() {
            bgimg.src = images[ i ];
        };
    }

    while( len-- ) {
        aElems[ len ].onmouseover = generateHandler( i );
    }
</script>

...placing it toward the bottom of the page, just before the closing </body> tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM