使用按钮激活函数- jQuery

8aqjt8rx  于 4个月前  发布在  jQuery
关注(0)|答案(4)|浏览(66)

我想用一个按钮来启用和禁用一个函数,在jQuery中可以吗?
我需要跟踪div上的所有点击,但只有当用户想要记录它们时。
1 -用户点击按钮“开始记录”2 -每次点击div都会记录数组中的坐标3 -当用户点击按钮“停止记录”时,数组保存在文件中,功能被禁用。
对于这个例子,我做了一个函数,它只是打印一个带有坐标的警报。

$('.room').click(function(e) {
                var width = $(this).css("width");
                var widthLength = width.length;
                var height = $(this).css("height");
                var heightLength = height.length;
                height = height.substring(0,heightLength-2);
                width = width.substring(0,widthLength-2);
                var posX = $(this).offset().left, posY = $(this).offset().top;
                posX = (e.pageX - posX);
                posY = (e.pageY - posY);
                posY = Math.round((100/height) * posY);
                posX = Math.round((100/width) * posX);
                alert(posX + " - " + posY);
    });

字符串
这就是div:

.room{
    position:relative;
    background-color:#444444;
    margin:5% 5% 10% 5%;
    z-index:1;
}

jfewjypa

jfewjypa1#

要做到这一点,你可以只保存你的点数组,以及一个是否正在记录的布尔值。每次点击都将一个新值推入数组-只有在记录时-当你点击停止时,可以对数组做任何你想做的事情。
举例来说:

var points = [];
var isRecording = false;
$('#start').click(function(){
    points = [];
    isRecording = true;
});

$('#stop').click(function(){
    isRecording = false;
    console.log(points);
});

$('.room').click(function(e) {
    if(isRecording){
      var width = $(this).css("width");
      var widthLength = width.length;
      var height = $(this).css("height");
      var heightLength = height.length;
      height = height.substring(0,heightLength-2);
      width = width.substring(0,widthLength-2);
      var posX = $(this).offset().left, posY = $(this).offset().top;
      posX = (e.pageX - posX);
      posY = (e.pageY - posY);
      posY = Math.round((100/height) * posY);
      posX = Math.round((100/width) * posX);

      points.push({x:posX,y:posY});
  }
});
.room{
  width:200px;
  height:200px;
  border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start Recording</button>
<button id="stop">Stop Recording</button>
<div class="room">
</div>
uoifb46i

uoifb46i2#

请按照以下步骤操作:

  • 有一个全局变量(例如:var canExcute=true)在默认情况下,你将能够执行函数
  • 然后在运行函数之前检查此变量
if(canExcute){
       function_to_run();
  }

字符串

  • 执行后,将变量设置为false(canExcute=false

希望它能给你灵感。

fzsnzjdm

fzsnzjdm3#

你可以声明一个全局布尔变量beRecord
当你点击开始录制按钮时,设置为true,反之则设置为false。
在记录函数的跟踪之前检查beRecord变量。

5m1hhzi4

5m1hhzi44#

你可以这样做:

var record = false;
      $('#yourbutton').click(function(e) {
        // toggle record true or false
        record = record ? false : true;
      });

      $('.room').click(function(e) {
          if(record){
            // only do your stuff if record is true               
          }
      });

字符串

相关问题