仅在单击按钮之前单击外部,才能关闭按钮

时间:2019-09-27 02:26:51

标签: javascript jquery html

通过单击按钮可以将其颜色从正(绿色)更改为负(红色)。我希望仅在按钮为红色时单击外部才能将其更改为绿色。

HTML

<button class="button13"></button>

CSS

.button13 {
  width: 25px;
  height: 25px;
  background: #70975B;
  margin-top: 30px;
  margin-left: 50%;
  transform: translate(-50%, -50%) rotate(0deg);
  border-radius: 100%;
  cursor: pointer;
  z-index: 100;
  transition: 0.4s cubic-bezier(0.2, 0.6, 0.3, 1.1);
}

.button13:after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 2px;
  width: 50%;
  background: white;
}

.button13:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 50%;
  width: 2px;
  background: white;
}

.button13.clicked {
  transform: translate(-50%, -50%) rotate(360deg);
  background: #CC2A41;
}

.button13.clicked:before {
  width: 0;
}

JS

$(".button13").click(function() {
  $(this).toggleClass("clicked");

});

因此,我添加了另一个功能,以便在外部单击时也可以单击该按钮。

$(document).click(function (e) {
    if (!$(e.target).is('.button13')) {
        $('.button13').toggleClass("clicked");
    }
})

但是事实证明,无论按钮是红色还是绿色,都将单击该按钮。 我当时正在考虑创建一个变量并编写如下算法:

int buttonstate = 0;
if(the button is clicked){
$(this).toggleClass("clicked");
buttonstate = 1;
}

if(click outside and buttonstate ==1){
$(this).toggleClass("clicked");
buttonstate = 0;
}

我不确定它是否真的可以解决我的问题,我只是使用伪Java来表达我的想法。有可能在JS中实现此功能吗?

这是我的代码: jsfiddle

谢谢。

1 个答案:

答案 0 :(得分:0)

切换前,应检查是否单击了按钮

$(document).click(function (e) {
    if (!$(e.target).is('.button13')) {
             if( $('.button13').hasClass("clicked"))
                    $('.button13').toggleClass("clicked");
    }
})
相关问题