css - 具有绝对定位和高度的 svg 在 Chrome 中行为不端

标签 css google-chrome svg

下面的 HTML 文件会在 Chrome 中产生一些特殊的东西,这取决于行 $("#canvas").height(100); 是否被注释。

<!DOCTYPE html>
<html>
    <body>
        <div style="margin-right: auto; margin-left: auto; width: 940px;">
            <div><h1>Title</h1></div>
            <div style="height: 50px;"></div>
            <svg id="canvas" style="width: 100%; position: absolute; left: 0px; z-index: -1;">
                <rect id="rect" x="0" y="0" width="100" height="100" fill="none" stroke-width="1" stroke="black"/>
            </svg>
            <div id="div1">Hi</div>
            <div id="div2"></div>
        </div>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
            function move() {
                var left = $("#div1")[0].getBoundingClientRect().left;
                $("#div2").text('left = ' + (left - 5));
                $("#rect").attr("x", left - 5);
                $("#canvas").height(100);
            }

            move();

            $(window).resize(function() {
                move();
            });
        </script>
    </body>
</html>

当在最大化的 Chrome 窗口中加载页面时,根据分辨率,div 的文本会更改为 left = N。事实证明,N 的值偏移了 7。这可以通过调整窗口大小使其不最大化然后再次最大化来看出。

当行 $("#canvas").height(100); 被注释掉时,这种奇怪的行为不会出现。您可以在这个 jsfiddle 中见证这一点:http://jsfiddle.net/jvPCM/1/ .您必须向左加宽“结果” Pane ,直到矩形不靠近左边缘,然后点击刷新才能看到不正确的绘图。如果您再次调整 Pane 大小,它将被修复。这是它的样子:

好:enter image description here错误:enter image description here

什么会导致这种情况?

仅供引用:这不会出现在 Firefox 中(具有讽刺意味的是,它首先需要设置高度)。

最佳答案

这是因为这两种浏览器呈现输出的方式。

Chrome 会在脚本准备好运行时立即呈现并运行脚本,事实证明它执行得非常快,页面仍在加载一些未知资源(jquery 已经加载到那里)。当我在我的浏览器中测试它时,这会导致出现奇怪的滚动条(当然会立即消失)。此滚动条更改页面宽度, Canvas 宽度由 100% 样式取决于它。 这整件事导致了您遇到的错误。

仅供引用:$(document).ready 也不起作用。

关于css - 具有绝对定位和高度的 svg 在 Chrome 中行为不端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15867034/

相关文章:

html - 创建每周日历模仿谷歌日历

HTML 电子邮件 - 不能限制宽度

javascript - 在 Chrome 扩展中动态附加 SVG Sprite

html - 垂直居中的元素,上面有最小边距/填充?

HTML/CSS div 宽度 px 在不同的浏览器中看到不同的结果

java - 禁用 Chrome 上的 native 事件?

google-chrome - Chrome 扩展 : Getting the source HTML of the current page on page load

android - 使用 HTML5 启用后置摄像头

html - SVG 剪切路径缩放

javascript - 包含 foreignObject 的可滚动 SVG 中的错误