我想在鼠标单击点上显示一个spinner。所以我写了一个代码,它在<body>空的地方工作正常,但是当我单击body内部的任何元素时,它的位置都不正确。见下文:



(function($) {
  $(document).ready(function() {

    $(window).click(function(e) {
      var relativeX = (e.pageX - $(e.target).offset().left),
        relativeY = (e.pageY - $(e.target).offset().top);

      $("#sp").addClass('spinner');
      $(".spinner").css({
        "left": -20 + relativeX,
        "top": -20 + relativeY
      });
      setTimeout(function() {
        $("#sp").removeClass('spinner');
      }, 800);
    });
  });
})(jQuery);

.spinner {
  width: 40px;
  height: 40px;
  margin: auto;
  background-color: #333;
  position: absolute;
  border-radius: 100%;
  z-index: 9;
  -webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
  animation: sk-scaleout 1.0s infinite ease-in-out;
}

@-webkit-keyframes sk-scaleout {
  0% {
    -webkit-transform: scale(0)
  }
  100% {
    -webkit-transform: scale(1.0);
    opacity: 0;
  }
}

@keyframes sk-scaleout {
  0% {
    -webkit-transform: scale(0);
    transform: scale(0);
  }
  100% {
    -webkit-transform: scale(1.0);
    transform: scale(1.0);
    opacity: 0;
  }
}

p {
  margin: 20px;
  padding: 20px;
  border: 2px solid;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="sp"></div>
<p>Click the BOX to see problem! It's ok on outsite! </p>





我无法解决此问题,请帮助我!

谢谢!

最佳答案

您可以只使用事件中的pageXpageY属性。



(function($) {
  $(document).ready(function() {

      $(window).click(function(e) {
          var relativeX = e.pageX,
              relativeY = e.pageY;

  $("#sp").addClass('spinner');
  $(".spinner").css({"left":-20 + relativeX ,
              "top":-20 + relativeY
           });
  setTimeout(function() {
      $("#sp").removeClass('spinner');
  }, 800);
      });
  });
})(jQuery);

.spinner {
  width: 40px;
  height: 40px;
  margin: auto;
  background-color: #333;
  position: absolute;
  border-radius: 100%;
  z-index: 9;
  -webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
  animation: sk-scaleout 1.0s infinite ease-in-out;
}

@-webkit-keyframes sk-scaleout {
  0% { -webkit-transform: scale(0) }
  100% {
    -webkit-transform: scale(1.0);
    opacity: 0;
  }
}

@keyframes sk-scaleout {
  0% {
    -webkit-transform: scale(0);
    transform: scale(0);
  } 100% {
    -webkit-transform: scale(1.0);
    transform: scale(1.0);
    opacity: 0;
  }
}
p{margin:20px; padding:20px;border:2px solid;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="sp"></div>
<p>Click the BOX to see problem! It's ok on outsite! </p>

09-13 02:49