当他在父元素之外时停止移动元素

时间:2017-11-26 18:02:44

标签: javascript html css

所以,我在右侧的箭头上有一个事件监听器keydown,当你推动正方形移动xPX但是我的父元素wh 例如设置一个100px,我想停止移动,我不能,我尝试使用element.offsetWidth > 0这样你就可以移动了。

请看这个小提琴:FIDDLE

2 个答案:

答案 0 :(得分:1)

代码中的错误很少。我已经评论了修复程序。以下是我为右箭头制作的方法 - 您可以对其余的动作应用相同的逻辑......

代码:

    const carre = document.querySelector('.carre');
    const main = document.querySelector('.main');
    const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code

carre.style.left="0px"; // set start position 
    document.addEventListener('keyup', (event) => {
        const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)

        if(event.keyCode == '39') {
            if (positionLeft < w) { // this was fixed too
                carre.style.left = (positionLeft) + 10 + 'px';
            } else {
                carre.style.left = '0'
            }
        }

    })

DEmo:

&#13;
&#13;
const carre = document.querySelector('.carre');
    const main = document.querySelector('.main');
    const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code

carre.style.left="0px"; // set start position 
    document.addEventListener('keyup', (event) => {
        const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)
     
        if(event.keyCode == '39') {
            if (positionLeft < w) { // this was fixed too
                carre.style.left = (positionLeft) + 10 + 'px';
            } else {
                carre.style.left = '0'
            }
        }
       
    })
&#13;
* {
  box-sizing:border-box;
}

.carre {
           position:absolute;
            left: 0;
            width: 50px;
            height: 50px;
            background-color: red;
        }
        .main {
            position: relative;
            width: 100px;
            height: 100px;
            border: 1px solid #000;
        }
&#13;
<main class="main">
    <div class="carre"></div>
</main>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我重建你的代码:

 document.addEventListener('keydown', (event) => {
        const w = main.getBoundingClientRect().right - carre.getBoundingClientRect().right;
        const positionLeft = carre.getBoundingClientRect().left;
        if(event.keyCode == '39') {
            if (w >= 0) {
                carre.style.left = (positionLeft) + 10 + 'px';
            } else {
                carre.style.left = '0'
            }
        }
        if (event.keyCode == '37') {
            if (w >= 0) {
                carre.style.left = (positionLeft) - 10 + 'px';
            }else {
                carre.style.left = '0'
            }
        }
    })
相关问题