1

我有以下 HTML 代码

<div id="container">
    <div id="fixed">Logo</div>
</div>​

然后是下面的 CSS 代码

#container {
    width: 400px;
    border: 1px solid red;
    float:right;
}

#fixed {
    float:left;
    width: 200px;
    border: 1px solid green;
}​

当我调整窗口大小时,我希望固定 div 在窗口边缘位于其开头时继续向右移动。

你知道用 CSS、javascript 或 HTML 做这件事的任何方法吗?

我在 jsfiddle 中创建了一个示例,您可以在http://jsfiddle.net/alvarezskinner/kRrdb/中查看它,如果您调整中间栏的大小,您将看到固定层保持静止。

4

2 回答 2

1

I don't think this does exactly what you want, but it at least gets closer. Change the container style to:

#container {
    width: 100%;
    border: 1px solid red;
    float:right;
    max-width:400px;
}

Instead of moving the fixed div, this will just make sure that the container doesn't get wider than the page, thereby ensuring that the fixed div doesn't go past the left of the page. Will this work well enough?

Here is a fiddle if you want it: http://jsfiddle.net/jdwire/kRrdb/2/

于 2012-11-09T15:34:53.660 回答
0

如果容器无法调整大小,您可以使用 javascript 执行以下操作:

window.onresize = function(event) {
    var fixed = document.getElementById("fixed");

    var winWidth = window.innerWidth;
    var containerWidth = document.getElementById("container").offsetWidth;
    var fixedWidth = document.getElementById("fixed").offsetWidth;

    var overlap = containerWidth - winWidth;

    if(overlap > 0) {
        // prevent the element from moving off-screen
        overlap = Math.min(overlap, fixedWidth);
    }else{
        overlap = 0;  
    }

    fixed.style.marginLeft = overlap + "px";
}

http://jsfiddle.net/kRrdb/4/

这可以更简洁。我已经扩展以使其更易于理解。

于 2012-11-09T15:51:00.257 回答