如何在悬停另一个div时更改div背景图像

时间:2014-06-11 11:08:33

标签: javascript html css

我使用一个 div 来显示图片。 div的 id 名称是第一个,我使用css给出了背景图像和悬停图像。现在我必须在悬停另一个div时悬停第一个div图像。

这里是示例

<div id="first"></div>

第一个div的默认背景图片是 - bgimg.jpg

第一个div的悬停图片是 - hoverbgimg.jpg

另一个DIV <div id="second"></div>

当我悬停第二个div 时,第一个div图像应该更改

4 个答案:

答案 0 :(得分:1)

这不能仅通过CSS完成。

在Js文件中添加以下JS代码

$(document).ready(function(){
   $("#second").on("hover", function(){
     $("first").css("background", "imagename.jpg");
   });

});

不要忘记先包含jquery文件。

答案 1 :(得分:0)

是的,如果您尝试使用jquery,它是可能的。试试这行代码,只需复制并粘贴:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#dd").hover(function(){
$("#ddd").css("background-color","yellow");
},function(){
$("#ddd").css("background-color","pink");
});
});
</script>
</head>
<body>

<div id="dd">Hover the mouse pointer over this paragraph.</div>
<div id="ddd">Hover the mouse pointer over this paragraph.</div>
</body>
</html>

答案 2 :(得分:0)

使用jquery,您可以捕获第二个div中的悬停事件,并在第一个div上实现mouseover和mouseout的操作:

$( "#second" ).hover(
         function() {
            $("#first").mouseover();
          }, function() {
            $("#first").mouseout();
          });

答案 3 :(得分:0)

看看下面的代码示例:

使用JavaScript:

<div id ="first" style="min-height: 100px;width: 100px; background-image: url('../Content/images/bgImage.JPG') "></div>

<div id ="second" style="width:100px;height: 100px;background-color:#191970" onmouseover="changeFirst(true)" onmouseout="changeFirst(false)"></div>

<script type="text/javascript" language="javascript">

    function changeFirst(isHover) {
        if (isHover) {
            document.getElementById('first').style.backgroundImage = "url('../Content/images/hoverBgImage.png')";
        } else {
            document.getElementById('first').style.backgroundImage = "url('../Content/images/bgImage.JPG')";
        }
    }

</script>

使用JQuery:

<div id="first" style="min-height: 100px; width: 100px; background-image: url('../Content/images/bgImage.JPG')"></div>

<div id="second" style="width: 100px; height: 100px; background-color: #191970"></div>

<script type="text/javascript" language="javascript">


    $('#second').hover(function () {
        $('#first').css('background-image', "url('../Content/images/hoverBgImage.png')");
    },
        function () {
            $('#first').css('background-image', "url('../Content/images/bgImage.JPG')");
        }
    );

</script>