【问题标题】:Get actual margins of an html element in c#在c#中获取html元素的实际边距
【发布时间】:2012-05-20 18:53:07
【问题描述】:

我需要在我的 c# 代码中获取 IHTMLElements 边距占用的实际像素数。我查看了它的 style 和 currentStyle 成员,但相关部分要么为 null,要么设置为“auto”。

在互联网上搜索显示了 javascript 中的 getCurrentStyle 函数,但我的 c# 代码中需要这些数字。

显然我对 js 和 html 以及一切都有些陌生...

那么,有没有办法在 c# 代码中获得用于元素边距(或任何其他测量值)的实际计算的像素数?

我忘了补充:在可预见的将来,这只会在 Internet Explorer 中使用

【问题讨论】:

    标签: c# html computed-style


    【解决方案1】:

    必须在 C# 代码中吗?通过脚本在客户端执行此操作可能更容易 - 例如,使用jQuery width()innerWidth()outerWidth() 的某种组合应该返回边距。

    【讨论】:

    • 我认为我需要能够访问 c# 中的数字。我正在处理很多我无法重新架构的现有代码或类似的东西。是否可以在脚本中生成我需要的数字,然后在 c# 中访问它?
    • 我也是一个新手,所以请注意我所说的话:但是从 C# 访问 JS 结果的一种方法是让 JS 将其结果写入 DOM(例如,作为DOM 中隐藏的文本节点)。
    【解决方案2】:

    Javascript 部分

    var elementToCalc = document.getElementById("你的元素");

    document.getElementById('txtHidMarginTop').value = parseInt ( elementToCalc.currentStyle.marginTop );
    document.getElementById('txtHidMarginLeft').value = parseInt ( elementToCalc.currentStyle.marginLeft;
    document.getElementById('txtHidMarginRight').value = parseInt ( elementToCalc.currentStyle.marginRight;
    document.getElementById('txtHidMarginBottom').value = parseInt ( elementToCalc.currentStyle.marginBottom );
    

    HTML 部分

    <input type='hidden' id='txtHidMarginTop' runat='server' />
    <input type='hidden' id='txtHidMarginLeft' runat='server' />
    <input type='hidden' id='txtHidMarginBottom' runat='server' />
    <input type='hidden' id='txtHidMarginRight' runat='server' />
    

    使用 runat='server' 将这些变量附加到 input type='hidden' 元素,然后您可以使用 DOM 元素的 Value 属性在 C# 中访问这些变量。

    C# 部分

     string marginTop = int.Parse ( txtHidMarginTop.Value );
        string marginLeft = int.Parse ( txtHidMarginLeft.Value );
        string marginRight = int.Parse ( txtHidMarginRight.Value );
        string marginBottom = int.Parse ( txtHidMarginBottom.Value );
    

    【讨论】:

      【解决方案3】:

      从 offsetWidth 中减去 IHTMLElement2.clientWidth 怎么样?

      有关指标的更多详细信息: http://msdn.microsoft.com/en-us/library/ms530302(v=vs.85).aspx

      【讨论】:

        猜你喜欢
        • 2013-07-06
        • 2017-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多