试着做一个点击就能移动的盒子

Trying to make box that i can move if i click on it

本文关键字:移动 盒子 一个      更新时间:2023-09-26

尝试使jquery脚本,允许我移动广场根据我的鼠标移动,如果我点击它。如果我点击这个方框,它基本上什么都不做。它不移动后点击框,我不知道为什么,谁能帮助我…

$(function(){
  var clicked=1;
  var ch,x,y,cy,cx;
  $('#box').on("click",function(){
    clicked=clicked+1;
    var ch=clicked%2;
    alert('ch'+ch);
  });
  alert('ifas');
  $('body').mousemove(function(){
    if(ch==0)
    {
      var x=event.pageX;
      var y=event.pageY;
      var cx=('#box').css("left");
      var cy=('#box').css("top");
      if(cx==='auto')
      {
        var cx=0;
      }else{
        var cx=cx.replace('px','')
        }
      if(cy==='auto')
      {
        var cy=0;
      }else{
        var cy=cy.replace('px','')
        }
      var cy=y-cy;
      var cx=x-cx;
      $('#box').css({
        top:cy,
        left:cx,
      });
    }
  });
});

css基本上是100x100的方框。https://jsfiddle.net/pL72en07/8/

你的主要问题是:

缺少$ in:

var cx=$('#box').css("left");
       ^ // missing
var cy=$('#box').css("top");
       ^

在第一次点击处理程序中为ch设置本地var。这意味着永远不会定义更高级别的ch,也永远不会更改

 $('#box').on("click",function(){
    clicked=clicked+1;
    ch=clicked%2; // remove `var`
    alert('ch'+ch);
  });

盒子现在移动了,虽然不太顺利,我不知道你的期望是什么。

如果你想在按下鼠标时用光标移动一个元素,并在鼠标位置再次按下鼠标时释放它,你可以这样做:

// Set the position attribute for the CSS style to absolute 
<div class="moveAble" style="position:absolute;">
    This div is movable!
</div>

JS

// Wait for the dom to be ready
$(document).ready(function(){
    // declare variable for the element
    var moveable = $('.moveAble'),
        // variables for x,y position
        x,y,
        // bool that indicates wether the element should move or not.
        isMoving = false;
    // When the element is clicked
    moveable.on('click', function() {
        // Set the bool to be not the value it currently is, making it a toggle
        isMoving = !isMoving;
        // Use mousemove method and capture the event (e)
        $(document).mousemove(function(e){
            // set the x and y variables
            x = e.pageX;
            y = e.pageY;
            // if isMoving is true, alter its top and left CSS attributes to the x and y coordinates for top and left
            if (isMoving) {
                moveable.css({'top': y,'left': x});
            }
        });
    });
});