javascript - 如何在 div 上使用 onclick 开始转换?

标签 javascript jquery html css

我正在开发一个小部件,为此我正在使用 jquery 的 addClass 和 removeClass 方法,但有些方法不起作用,请帮助我解决这个问题。

代码如下:

$('#test').click(function() {
  $(this).addClass('second');
  console.log("hello");
}, function() {
  $(this).removeClass('second');
});
   #test {
     transition: all 0.5s ease;
   }
   .first {
     width: 150px;
     height: 30px;
     position: fixed;
     bottom: 0px;
     right: 25px;
   }
   #prop {
     width: 150px;
     height: 30px;
     position: fixed;
     bottom: 0px;
     right: 25px;
     background-color: #abc322;
     color: white;
     text-align: center;
   }
   .second {
     width: 150px;
     height: 300px;
     position: fixed;
     bottom: 0px;
     right: 25px;
     box-shadow: 3px 4px 40px grey;
   }
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div id="test" class="first">
  <div id="prop">
    freight Calculator
  </div>
  <p>
    welcome to freight calculator
  </p>
</div>

当我单击 div 时,它应该更改其类并开始过渡,但它不起作用。请指出我所犯的错误。

感谢您的宝贵时间。

最佳答案

jQuery .click()将一个函数作为事件监听器。您可以使用 .toggleClass()相反。

$('#prop').click(function(e) {
  e.preventDefault();
  $('#test').toggleClass('second');
});
#test {
  transition : all 0.5s ease;
}
.first {
  width: 150px;
  height: 30px;
  position: fixed;
  bottom: 0px;
  right: 25px;
}
#prop {
  cursor: pointer;
  width: 150px;
  height: 30px;
  position: fixed;
  bottom: 0px;
  right: 25px;
  background-color: #abc322;
  color: white;
  text-align: center;
}
.second {
  width: 150px;
  height: 300px;
  position: fixed;
  bottom: 0px;
  right: 25px;
  box-shadow: 3px 4px 40px grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test" class="first">
  <div id="prop">
    freight Calculator
  </div>
  <p>
    welcome to freight calculator
  </p>
</div>

关于javascript - 如何在 div 上使用 onclick 开始转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37566478/

相关文章:

javascript - 为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

javascript - OOP Javascript - 引用错误

javascript - Angularjs 范围变量未按预期更新

html - 具体表布局

html - 如何使用 CSS 仅将 HTML 选项元素的首字母大写?

javascript - 如何使用 $http 服务请求 API 数据

javascript - 从另一个 JSAppleScript 运行另一个 JS AppleScript 时出现权限错误

javascript - 如果我的文本区域为空,请使用 jquery 执行此操作

jquery - 在 div 中嵌套一个链接,该 div 被一个链接包围

javascript - 即 : First list item smaller than rest