为什么此代码会导致div消失?

时间:2019-02-07 17:57:13

标签: jquery html css onclick toggle

我已经搜索了过去几个小时,以找出导致div消失的原因。我正在尝试使背景色在点击时切换。基本上,我希望选择背景时变暗,以表明它已被选择。然后在再次单击后返回到正常状态。

我正在使用jQuery 3.3.1

这里是JSFiddle

HTML

<div id="readMailFunctionCellReply"><img src="images/reply.png" title="Reply" /><br>Reply</div>

CSS

#readMailFunctionCellReply{
justify-content: center;
padding-top:10px;
padding-bottom:5px;
text-align: center;
/* border: 1px solid #a45127; */
color:#a45127;
}
#readMailFunctionCellReply:hover{
cursor:pointer;
background-color: #ffedc5;
text-decoration: underline;
color:#a45127;
}

JavaScript

$(document).on('click', '#readMailFunctionCellReply', function() {

   $("#readMailFunctionCellReply").toggle(
      function() { 
         $("#readMailFunctionCellReply").css("background-color:#ffedc5");
      },
      function() {
         $("#readMailFunctionCellReply").css("background-color:");
      }
   );
})

感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

您要查找的不是.toggle,而是.toggleClass。第一个实际上是切换元素本身,隐藏并显示它。另一方面,Toggleclass会执行其在锡盒上所说的操作,它会在元素中弹出css类。 您所需要做的就是实现匹配的CSS类。

JS:

gradlew test

CSS:

$(document).on('click', '#readMailFunctionCellReply', function() {
    $("#readMailFunctionCellReply").toggleClass("selected"); 
});

JsFiddle,使用粉红色添加pizzaz: https://jsfiddle.net/6kswc9ug/

答案 1 :(得分:1)

使用toggleClass()而不是toggle()(并将类添加到CSS中):

CSS:

 #readMailFunctionCellReply{
  justify-content: center;
  padding-top:10px;
  padding-bottom:5px;
  text-align: center;
  /* border: 1px solid #a45127; */
  color:#a45127;
}
#readMailFunctionCellReply.selected{
  background-color:#ffedc5;
}
#readMailFunctionCellReply:hover{
  cursor:pointer;
  background-color: #ffedc5;
  text-decoration: underline;
  color:#a45127;
}

JS:

$(document).on('click', '#readMailFunctionCellReply', function() {

    $("#readMailFunctionCellReply").toggleClass("selected");

})

或JS:

$('#readMailFunctionCellReply').click(function() {

  $(this).toggleClass("selected");

})

toggle()函数更改显示属性(显示或隐藏匹配的元素)。检查the documentation了解更多详细信息。

答案 2 :(得分:1)

根据您的需要,我为您提供以下代码。

$("#readMailFunctionCellReply").click(function(){
			$("#readMailFunctionCellReply").toggleClass("orangeBG");
});
#readMailFunctionCellReply{
	justify-content: center;
	padding-top:10px;
	padding-bottom:5px;
	text-align: center;
	/* border: 1px solid #a45127; */
	color:#a45127;
}
#readMailFunctionCellReply:hover{
	cursor:pointer;
	background-color: #ffedc5;
	text-decoration: underline;
	color:#a45127;
}
.orangeBG {
  background-color: #ffedc5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="readMailFunctionCellReply"><img src="images/reply.png" title="Reply" /><br>Reply</div>

答案 3 :(得分:1)

您需要删除:

 $("#readMailFunctionCellReply").toggle(function()

切换功能切换项目的可见性,而您需要使用addClass或toggleClass。

我有一个工作的小提琴:

https://jsfiddle.net/Preston17/vo4kaj6d/