当窗口撞到边框时,使用变换停止div

时间:2014-03-05 16:35:50

标签: javascript jquery css border transform

我使用css变换制作了一个查看器,我当前想知道的是,当div的边框碰到窗口边框或者我应该放弃变换方法时,我可以阻止它移动吗?

这是代码http://jsfiddle.net/pool4/W2vub/3/

var x=0, 
    y=0,
    rateX=0,
    rateY=0,
    maxspeed=10;
var container = $('.container');

var w = container.width() / 2;
var h = container.height() / 2;
var center = {
    x: container.offset().left + container.width() / 2,
    y: container.offset().top + container.height() / 2
};

container.on('mousemove', function(e){   
    var offsetX = e.pageX - center.x;
    var offsetY = e.pageY - center.y;

    rateX = -offsetX / w;
    rateY = -offsetY / h;
});

container.hover(
    function(){
        var scroller = $(this).data('scroller');
        if (!scroller) {
            scroller = setInterval( moveContent, 30 );
            $(this).data('scroller', scroller);
        }
    },
    function(){
        var scroller = $(this).data('scroller');
        if (scroller) {
            clearInterval( scroller );
            $(this).data('scroller', null);
        }
    }
);   

function moveContent(){
    x += maxspeed * rateX;
    y += maxspeed * rateY;
    var newpos = 'translate('+x+'px, '+y+'px)',
        transform = '-webkit-transform' || '-moz-transform' || '-ms-transform' ||  '-o-transform'  || 'transform',
        content = $('.content');
    content.css(transform ,newpos);
}

1 个答案:

答案 0 :(得分:1)

您可以尝试创建一些边界,只需在超出它们时将变换设置为这些边界:

function moveContent(){
    x += maxspeed * rateX;
    y += maxspeed * rateY;

    // top and left boundaries
    x = x > 0 ? 0: x;
    y = y > 0 ? 0: y;

    // create my bottom and right boundaries
    var x_bound = -$('.content').width() + $(window).width();
    var y_bound = -$('.content').height()+ $(window).height();
    x = (x < x_bound) ? x_bound : x;
    y = (y < y_bound) ? y_bound : y;

    var newpos = 'translate('+x+'px, '+y+'px)',
    transform = '-webkit-transform' || '-moz-transform' || '-ms-transform' ||  '-o-transform'  || 'transform',
        content = $('.content');
    content.css(transform ,newpos);
}

这是更新后的FIDDLE

注意:在小提琴中,我使用了1500而不是$('.content').width(),因为该div的宽度并不代表组合框的宽度。