调整大小时左右移动div

时间:2015-02-14 18:32:05

标签: javascript html css resize

我有一个在调整大小时向右移动的框,直到它在半屏宽度消失。

    function move() {
        var x = screen.width - window.innerWidth;
        document.getElementById("logo").style.marginLeft = (x * 2) + "px";
    }
    window.onresize = move;

我希望那个盒子在它撞到窗户边缘时以向右移动的方式逐渐向后移动。

    function move() {
        var x = screen.width - window.innerWidth;
          do {
        document.getElementById("logo").style.marginLeft = (x * 2) + "px";
        } while (window.innerWidth > "850px");
          do {
        document.getElementById("logo").style.marginLeft -= (x * 2) + "px";
        } while (window.innerWidth > "850px");
        }
    window.onresize = move;

上面的代码就好像第二个语句是不存在的

1 个答案:

答案 0 :(得分:0)

假设#logo的宽度= 100px; 你可以这样做,当#logo到达屏幕边缘时,它将保持在那里。

function move() {
    var pos = 0;
        x = screen.width - window.innerWidth,
        winWidth = (window.innerWidth/2)-50;
        if (x < winWidth) {
            pos = x*2;
        }
        else {
            blockPos = (winWidth - x);
            pos = parseInt(document.getElementById("logo").style.marginLeft) +blockPos;
        }
        if (pos < 0) pos = 0;
        document.getElementById("logo").style.marginLeft = pos+"px";
    }
window.onresize = move;