jquery collision detection for divs

别来无恙 提交于 2019-12-11 08:45:55

问题


I'm trying to learn some programming with jQuery. I have a div that has 800 x 800 pixel dimensions. I have another 16 x 16 pixel div that I want to move within the bigger one using arrow keys. Problem is I can't get it to work properly, can someone please tell me what I'm doing wrong.

Moving left works, it stops the 16x16 div if css attribute "left" is under 0px:

$(this).keydown(function(e) {  
    if (e.which == '37' && ($('#p1').css('left') > "0px")) {
        $('#p1').css('left', '-=16px')
    }
});

Moving right doesn't work, it stops the 16x16 div at 80px from the left, no matter what value above 80px I try:

$(this).keydown(function(e) {  
    if (e.which == '39' && ($('#p1').css('left') < '800px')) {
        $('#p1').css('left', '+=16px')
    }
});

Also moving up and down using similar method doesn't work, movement is restricted incorrectly. Moving in all direction works fine without && arguments.


回答1:


Taking the answer from jermel as well I would also clean up the code a bit to something like this

$(document).ready(function() {

    $(document).keydown(function(e){
        var left = parseInt($('#p1').css('left'),10);

        if (e.keyCode === 37  && (left > 0)) {
            $('#p1').css('left', left-16);
        }



        if (e.keyCode === 39 && (left < 800)) {
            $('#p1').css('left',left+16);
        }



    });


});



回答2:


Your problem is:

css('left') < '800px')

You are comparing strings instead of numbers;

Try:

var left = parseInt($('#p1').css('left'),10);
if (e.which == '39' && (left < 800)) {...


来源:https://stackoverflow.com/questions/8829421/jquery-collision-detection-for-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!