使用一个按钮来启动和停止一个功能,而不是两个按钮

Using one button to enable and stop a function rather than two buttons

本文关键字:按钮 一个 功能 两个 启动      更新时间:2023-09-26

我目前使用两个按钮(Go, Stop)来调用和启用/禁用我的功能。但是是否可以使用一个按钮来调用函数来禁用或启用。例如,单击按钮将使其变为蓝色,这将启用该功能,再次单击按钮将使其变为白色,这将禁用该按钮。

我当前的代码是:

<button id="go">Go</button>
<button id="stop">STOP!</button>
<div class="block"></div>
   <style>
  #draggable {
   width: 150px;
    height: 150px;
     padding: 0.5em;
     top:5%;
     left: 5%; }
  </style>
<script>
// Start animation
$( "#go" ).click(function() {
  $( ".block" ).draggable();
});
// Stop animation when button is clicked
$( "#stop" ).click(function() {
$( ".block" ).draggable( "disable" );
});
$( "#go" ).click(function() {
$( ".block" ).draggable( "enable" );
});
</script>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<div class="block"></div>
   <style>
  #draggable {
   width: 150px;
    height: 150px;
     padding: 0.5em;
     top:5%;
     left: 5%; }
  </style>
<script>
// Start animation
$( "#go" ).click(function() {
  $( ".block" ).draggable();
});
// Stop animation when button is clicked
$( "#stop" ).click(function() {
$( ".block" ).draggable( "disable" );
});
$( "#go" ).click(function() {
$( ".block" ).draggable( "enable" );
});
</script>

当然,您所需要的只是跟踪状态的东西,比如标志

$("#go").on('click', function () {
    var flag = $(this).data('draggable');
    $(".block").draggable( flag ? 'disable' : 'enable' );
    $(this).data('draggable', !flag);
});

小提琴

可以试试jquery在你的点击功能

$(this).toggleclass("stop")
*insert code to test if class is stop"