我该如何用Javascript编写此jQuery代码?

时间:2019-09-11 12:32:48

标签: javascript jquery

此练习中,我需要一个函数,当我用鼠标左键单击时,会将div随机移到body内。

我很难将这段代码(jquery)交换为javascript。会怎么样?

var counter = 0;
var div = document.getElementsByClassName('a');

function click() {
  if (counter < 1) {
    var pos = makeNewPosition();
    this.style.left = pos[1] + 'px';
    this.style.top = pos[0] + 'px';
  }
}

function makeNewPosition() {

  // Get viewport dimensions (remove the dimension of the div)
  var h = window.innerHeight = -50;
  var w = window.innerWidth = -50;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  return [nh, nw];

}
<div onclick="click()" class="a">Click</div>

这是我想在jQuery中编写的javascript

$(document).ready(function(){

var counter = 0;

    $('.a').click( function () {
        if (counter < 1 ) {
            var pos =  makeNewPosition();
            this.style.left = pos[1] +'px';
            this.style.top  = pos[0] +'px';
        }
    });
});

function makeNewPosition(){

    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh,nw];    

}

2 个答案:

答案 0 :(得分:1)

JavaScript:

window.addEventListener("load", function() {
  var counter = 0,
    div = document.querySelector(".a");

  div.addEventListener("click", function() {
    if (counter < 1) {
      var pos = makeNewPosition();
      this.style.left = pos[1] + 'px';
      this.style.ltop = pos[0] + 'px';
    }
    counter++;
  });
});

function makeNewPosition() {

  // Get viewport dimensions (remove the dimension of the div)
  var h = window.innerHeight -50;
  var w = window.innerWidth  -50;
  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  return [nh, nw];

}
.a {
  position: absolute;
  top: 100;
  left: 100
}
<div class="a">Click</div>

基于此jQuery:

$(function() {

  var counter = 0;

  $('.a').click(function() {
    if (counter < 1) {
      var pos = makeNewPosition();
      $(this).css({
        "left": pos[1] + 'px',
        "top": pos[0] + 'px'
      });
    }
    counter++;
  });
});

function makeNewPosition() {

  // Get viewport dimensions (remove the dimension of the div)
  var h = $(window).height() - 50;
  var w = $(window).width() - 50;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  return [nh, nw];

}
.a {
  position: absolute;
  top: 100;
  left: 100
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">Click</div>

答案 1 :(得分:0)

最惯用的方法是首先获取对该元素的引用

const div = document.getElementsByClassName('a')[0];

然后将事件监听器添加到元素

div.addEventListener('click', click); //Attach your handler function to the event