简体   繁体   English

Javascript添加div背景图片?

[英]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. 我正在尝试使div背景图像在您将鼠标悬停在其上时进行更改以及更改文本颜色。 I got the color changing ok, but the bg image isn't. 我可以更改颜色,但是bg图像不是。 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 . HTMLElementstyle属性没有称为background-image属性。

u can do it with simple css too demo 你也可以用简单的CSS 演示

or with Javascript demo1 或使用Javascript demo1

css: CSS:

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

u can try this: 你可以试试看

css: CSS:

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

js: js:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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