setInterval函数,用于在过渡时重叠的元素,

时间:2019-03-14 06:39:52

标签: javascript function methods setinterval overlap

我想优化。使用setInterval检查蓝色/绿色是否重叠,如果蓝色确实在绿色以下发送,直到不再相交为止。但是,很多时候它们并没有相交,而是可能彼此相距更远或更近,但并没有完全重叠。当绿色/蓝色将要重叠而不是不重叠时,有什么检查重叠的方法?这可以更简单吗?同样,我对这种方法的使用不像本例那样使用均等反相关的变量,因此(例如rand> 50%)解决方案将无济于事。谢谢!

var green = document.getElementById('green');
var blue = document.getElementById('blue');
        
function myFunct1() {
    var array = ['10%','20%','30%','40%','50%','60%','70%','80%']  
    var rand = array[Math.floor(Math.random()*array.length)];
    green.style.left = rand;
    blue.style.right = rand;
    var inter = setInterval(overlay, 50);
    setTimeout(function( ) { clearInterval( inter ); }, 1500);
}

function overlay() {
    var greenRect = green.getBoundingClientRect();
    var blueRect = blue.getBoundingClientRect();
    var overlap = !(greenRect.right < blueRect.left || greenRect.left > blueRect.right)
            
    if (overlap == true) {
        blue.style.top = '20px';  
    }
    else {
        blue.style.top = 'auto';
    }
}
#container {
   position: relative;
   width: 90%;
   height: 40px;
   margin: auto;
   border: 1px solid black;
 }

#green {
  position: absolute;
  width: 50px;
  height: 20px;
  left: 10px;
  background-color: green;
  transition: 1500ms;
 }
        
#blue {
  position: absolute;
  width: 50px;
  height:20px;
  right: 10px;
  background-color: blue;
  transition: 1500ms;
}
<div id = 'container'>
    <div id = 'green'></div>
    <div id = 'blue'></div>
</div>
        
<button onclick = 'myFunct1()'>FUNCTION 1</button>

1 个答案:

答案 0 :(得分:0)

如何增加一些重叠公差,

我只是在两个方框之一上添加了一个,但是,当然,您可以拆分重叠部分并将其应用于两个方框中

function overlay() {
    var overlappingTolerance = 10
    var greenRect = green.getBoundingClientRect();
    var blueRect = blue.getBoundingClientRect();
    var overlap = !(
                       ( greenRect.right - overlappingTolerance)  < blueRect.left ||
                       ( greenRect.left - overlappingTolerance) > blueRect.right
                   );

    if (overlap == true) {
        blue.style.top = '20px';  
    }
    else {
        blue.style.top = 'auto';
    }
}