j查询在悬停时更改背景

jQuery changing background on hover

本文关键字:背景 悬停 查询      更新时间:2023-09-26

我有这个代码

.html

<div id="addQuesion">
    <ul id="aQul">
        <li class="aQli"></li>
        <li class="aQli"></li>
    </ul>
</div>

我的jQuery是

jQuery

$(document).ready(function(){
    $(".aQli").mouseover(function(){
    });
    $(".aQli").mouseout(function(){
    });
});

我希望当将鼠标悬停在 li 上时,背景应该是红色的,在退出该 li 时,背景应该恢复为白色。 我该怎么做?

你必须使用 jQuery 吗?

更"正确"的方法是向类添加悬停样式。

.aQli:hover{
   background-color: red;   
}​

有关示例,请参阅此处。 http://jsfiddle.net/maurice_butler/5q6QM/

你可以简化它以使用 .hover():

$(document).ready(function(){
    $(".aQli").hover(function(){
        $(this).css("background", "#F00");
    },
    function(){
        $(this).css("background", "#FFF");
    });
});

第一个函数用于鼠标悬停,第二个函数用于鼠标退出。 .css() 函数设置 CSS 属性,在本例中为悬停元素的背景色。

$(function(){
    $(".aQli").on('mouseover', 'li', function(){  //using "on" for optimization
        this.style.backgroundColor = 'red';       //native JS application
    }).on('mouseout', 'li', function(){           //chain to avoid second selector call
        this.style.backgroundColor = 'white';     //native JS application
    })
});

我想出了两种使用jQuery的方法。一种方法是使用 jQuery 直接更改 css,使用 .css() 设置背景颜色。

//css
ul#aQul li{
  display : inline-block;
  padding : 5px;
  margin : 5px;
}
//javascript use jQuery
$(document).ready(function(){
 $(".aQli").mouseover(function(){
    $(this).css({
        "background-color" : "red",
        "cursor" : "pointer"
    });
 });
 $(".aQli").mouseout(function(){
    $(this).css({
        "background-color" : "transparent",
        "cursor" : "default"
    });
 });
});​​

另一种方法是在发生悬停时使用jQuery添加特定的类属性,并且有一个特定的css规则来更改背景颜色。

//css, need to specify the state of hover
 ul#aQul li.hover{     //li elements which have "hover" class
   cursor:pointer;
   background-color : red;
 }
//javascript
$(document).ready(function(){
 $(".aQli").mouseover(function(){
    $(this).addClass("hover")      //hover, add class "hover"
 });
 $(".aQli").mouseout(function(){
    $(this).removeClass("hover");  //hover out, remove class "hover"
 });
});​

$(document).ready(function(){
    $(".box").hover(function(){
        $(this).css("background-image", "url(ENETR URL HERE)");
    },
    function(){
        $(this).css("background", "#FFF");
    });
});
.box{
  width:200px;
  height:200px;
  border: 1px solid black;
}
<html>
<head>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
  <div class="box">
    
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="js/script.js"></script>
</body>
</html>