为什么这个代码导致DIV消失?

问题描述 投票:1回答:4

我搜索在过去的几个小时搞清楚为什么这会导致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:");
      }
   );
})

谢谢你的帮助!

jquery html css onclick toggle
4个回答
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
投票

你要找的是不是.toggle.toggleClass。第一个实际切换元素本身,隐藏和显示它。 Toggleclass,另一方面做什么它在锡说,它弹出进出元素的CSS类。所有你需要的是落实匹配CSS类。

JS:

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

CSS:

#readMailFunctionCellReply.selected{
    background-color: pink;
}

的jsfiddle,用粉红色添加丰富有趣:https://jsfiddle.net/6kswc9ug/


1
投票

您需要删除:

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

该项目的切换功能切换的知名度,而你需要使用addClass或toggleClass。

我有一个工作小提琴:

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


1
投票

使用toggleClass()而不是切换()(并添加类到你的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");

})

肘节()函数改变显示属性(显示或隐藏匹配元素)。检查the documentation了解更多详情。

© www.soinside.com 2019 - 2024. All rights reserved.