javascript - .hover() 在 jQuery 中不起作用

标签 javascript jquery html css hover

我尝试创建一个 jQuery 函数 .hover 来更改 div 的背景颜色,方法是使用另一个类并使用 hover 来添加类和删除类。

HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<script type='text/javascript' src='script.js'></script>
<title>Untitled 1</title>
</head>
<body>
<div>HOME</div>
<div>ABOUT</div>
<div>CONTACT</div>
</body>
</html>

CSS:

div {

                display:inline;
                font-family: Helvetica;
                color: white;
                background-color:#FF6666;
                padding: 20px;
}
.hltd {
                display:inline;
                font-family: Helvetica;
                color: black;
                background-color:#66FF33;
                padding: 20px;


}

Javascript:

$(document).ready(function(){

  $('div').hover(
    function(){
    $(this).addClass('hltd');
    },
    function(){
    $(this).removeClass('hltd');
    }
  );

});

最佳答案

您还没有包含 Jquery 库。将其包含在您的脚本之前:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='script.js'></script>

$(document).ready(function() {

  $('div').hover(
    function() {
      $(this).addClass('hltd');
    },
    function() {
      $(this).removeClass('hltd');
    }
  );

});
div {
  display: inline;
  font-family: Helvetica;
  color: white;
  background-color: #FF6666;
  padding: 20px;
}
.hltd {
  display: inline;
  font-family: Helvetica;
  color: black;
  background-color: #66FF33;
  padding: 20px;
}
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link type="text/css" rel="stylesheet" href="stylesheet.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script type='text/javascript' src='script.js'></script>
  <title>Untitled 1</title>
</head>

<body>
  <div>HOME</div>
  <div>ABOUT</div>
  <div>CONTACT</div>
</body>

</html>

不过,如果您只想更改背景颜色,CSS 会是更好的选择。

关于javascript - .hover() 在 jQuery 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29581060/

相关文章:

javascript - 带有 Angular 和 Bootstrap 的日期选择器绑定(bind)

html - 我的第一个基于 HostGator 的网站没有连接 html 和 css

javascript - 使用javascript动画div的位置

javascript - 存储带有多个彼此相邻的撇号的字符串

php - Jquery:验证表单而不刷新页面

javascript - 使用复选框和简单形式 gem 禁用和启用

html - MDC 网格布局不会根据设备更改

javascript - 未捕获的 TypeError : getUsername(. ..).then 不是一个函数

javascript - 使用 javascript 检查 html 表单的结果

jquery - 如何使用当前元素 $(this) 的 JQUERY 生成选择器?