HTML元素相互接触[重复]

This question already has an answer here:

I have a button, and two HTML elements. After pressing the button, i called animate function from j query to start moving the first element to right and let two HTML elements get touched.

How i will detect that two HTML elements get touched?

Need Help. Thanks in advance.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script> 
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").animate({
      left:'250px',
    });
  });
});
</script> 
</head>

<body>
<button>Start Animation</button>
<div id = "div1" style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div>
<div id = "div2" style="background:#98bf21;height:100px;width:100px;position:absolute;left:50%;right:50%">
</div>

</body>
</html>
</div>

Your elements won't ever touch, because your selector $('div') which you are animating will animate both divs and move them both by the same amount. They will end up the same distance apart.

Also, you can't use <div2> as a tag name. Instead, use an id attribute to assign them a unique name, like this:

<div id="div1"></div>
<div id="div2"></div>

Then instead of animating $('div'), animate $('#div1').

You can first get the `left` position of `#div2` in pixels and use that value to animate the `right` position of `#div1` to exactly that spot, like this: $(document).ready(function(){ // when the buttom is clicked $('button').click(function(){ // get the left position of div2 var div2Left = $('#div2').position().left // animate so that the right side of div1 matches div2's left $('#div1').animate({ 'right': div2Left + 'px', }); }); });

--EDIT--

I misread your question, I thought you were asking how to get them to touch. If you want to detect that they have overlapped, you can use the step function of the animation to check if the right side of div1 crosses the left side of div2. Try this:

$(document).ready(function(){
  // when the buttom is clicked
  $('button').click(function(){
    // get the left position of div2
    var div2Left = $('#div2').position().left
    // animate so that the right side of div1 matches div2's left
    $('#div1').animate({
      'right': '250px',
    }, {
        // this is called every step of the animation 
        step: function(currentRightPos) {
          // check if collision occurs
          if (currentRightPos >= div2Left) {
            console.log('The divs collided!');
          }
        }
    });
  });
});