简体   繁体   中英

Javascript to add div background image?

I am trying to get a div background image to change when you roll over it as well as change text color. I got the color changing ok, but the bg image isn't. Here's what I got:

In the head:

#menu1 {
    background-image: none;
}

<script language="javascript">
function txtroll(x)
{
x.style.color="white";
x.style.background-image="url(images/moragames/logo/moragames_logo_01.png);
}
</script>

In the body:

<div id="menu1" onmouseover="txtroll(this)" onmouseout="txtout(this)">

I cannot seem to get the rollover to add the background image but it changes the font color just fine. Any ideas what I'm doing wrong? Thanks!

Try -

x.style.backgroundImage="url(images/moragames/logo/moragames_logo_01.png)";

instead of -

 x.style.background-image="url(images/moragames/logo/moragames_logo_01.png) 

The style property of HTMLElement has no property called background-image .

u can do it with simple css too demo

or with Javascript demo1

css:

#menu1 {
    background-image: none;
    height:100px;
}
#menu1:hover {
    background-image: url('http://placekitten.com/200/100');
}

u can try this:

css:

.hover {
    background-image: "url(images/moragames/logo/moragames_logo_01.png)";
}

js:

$('#menu1').on('mouseover', function(){
    $(this).addClass('hover');
}).on('mouseout', function() {
    $(this).removeClass('hover');
});

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