【问题标题】:Element dimensions are updating in the DOM but the changes aren't displaying onresizeDOM 中的元素尺寸正在更新,但更改未显示 onresize
【发布时间】:2012-07-22 07:21:07
【问题描述】:

我正在尝试调整svg 元素的大小以尽可能大地适应浏览器,同时保持100x50 的比例。当我检查对 DOM 所做的更改时,一切正常,但更新后的尺寸似乎没有呈现。我该如何解决这个问题?

http://jsfiddle.net/Wexcode/SE6d3/show/

var svg = document.getElementById("svg");
resize.call(svg);

window.onresize = function() {
    resize.call(svg);
}

function resize() {    
    this.setAttribute("width", scale(100));
    this.setAttribute("height", scale(50));

    function scale(value) {
        return Math.min(window.innerWidth / 100, window.innerHeight / 50) * value;
    }
}

编辑: sq2's answer,将代码从

    this.setAttribute("width", scale(100));
    this.setAttribute("height", scale(50));

    this.style.width = scale(100);
    this.style.height = scale(50);

提供了修复,但在 Firefox 中仍然存在问题。

【问题讨论】:

  • 我想我误解了一些东西。我在最新的 Firefox 中打开演示,尝试调整浏览器窗口的大小,黑框总是调整大小,使其宽度和高度保持 2:1 的比例。应该怎么做?
  • @duri - 以上版本在 Chrome 中不起作用。使用 this.style[attribute] 修复 Chrome,但在 Firefox 中不起作用。见:jsfiddle.net/Wexcode/SE6d3/16/show
  • 我可能遗漏了一些东西,但你为什么不直接通过 CSS 调整大小呢? jsfiddle.net/RqUY3
  • @Duopixel - 不会产生 100x50 的比例。
  • 使用 Math.min 而不是 'minimum'

标签: javascript html css firefox svg


【解决方案1】:

更新: 此外,这个http://jsfiddle.net/SE6d3/70/ 在任何地方都可以使用,并且 resize 可以在 Chrome 和 Firefox 中使用,比例为 100 到 50

编辑:设置宽度/高度 CSS 样式,而不是设置宽度/高度属性。


你在属性/风格层面没有问题:试试这个http://jsfiddle.net/SE6d3/27/ 如果Firefox和chrome都可以正常工作。

我认为您的问题在于从窗口获取宽度/高度的水平。 试试这个方法:

getClientHeight = function(){
    return document.compatMode=='CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight;
};

getClientWidth = function(){
  return document.compatMode=='CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth
};

【讨论】:

    【解决方案2】:

    不知道为什么它会间歇性工作,非常奇怪和好奇是否有更好的答案。

    但是...替换:

    this.setAttribute("width", scale(100));
    this.setAttribute("height", scale(50));
    

    与:

    this.style.width = scale(100);
    this.style.height = scale(50);
    

    在 Chrome 的屏幕上正确呈现它,但是我怀疑设置 SVG 的样式是正确的方法。

    【讨论】:

    • 有趣。我很好奇为什么设置属性不起作用,但这也很好。谢谢。
    • 经过进一步审查,不幸的是,Firefox 仍然坏了。
    猜你喜欢
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2014-01-20
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 2014-09-17
    相关资源
    最近更新 更多