获取嵌套在聚合物纸张对话框中的自定义Web组件内内容的客户端高度

Get clientHeight of content inside custom web-component nested in Polymer paper-dialog

本文关键字:Web 自定义 组件 高度 客户端 嵌套 聚合物 对话框 获取      更新时间:2023-09-26

我会尽量把我的问题解释得最清楚。

我正在使用<paper-dialog><paper-dialog-scrollable>.

<paper-dialog-scrollable>我有一个表格,它是一个自定义web-component

在这种形式中,我使用另一个自定义web-component来展开和折叠内容。

内容的默认状态为折叠。

在 expandcomponent 中,我将内容的clientHeight保存在变量contentHeight中,并将内容的height设置为 0。

我有一个函数toggle(),它在单击触发器时执行。

toggle()将内容

height设置为 contentHeight

现在,当我单独使用我的表单或扩展组件时,这非常有效,但是当它们嵌套在paper-dialog中时,它不起作用,因为clientHeight为 0。

法典:

<paper-dialog with-backdrop style="min-width: 90%;">
   <paper-dialog-scrollable>
      <my-custom-form-component></my-custom-form-component>
   </paper-dialog-scrollable>
</paper-dialog>

来自<my-custom-form-component>的代码:

<div id="custom-expand-component-trigger"></div>
<custom-expand-component trigger="custom-expand-component-trigger">
   blabla a lot of content......
</custom-expand-component>

toggle()功能(<custom-expand-component>内部):

function toggle(){
  if(!that.opened){
    content.style.height = contentHeight + 'px';  //contentHeight is 0 when form is nested in <paper-dialog>
  } else{
    content.style.height = startHeight;
  }
  that.opened = !that.opened;
}

任何想法,即使我的表单在对话框中,我如何获得clientHeight?

我希望这已经足够清楚了。

帮助将不胜感激

隐藏

元素的clientHeight为 0,因此在呈现之前无法获取它。

<paper-dialog>打开时,元素实际上首先呈现。发生这种情况时,将触发iron-overlay-opened事件。如果您以前没有设置过,这是一个获得正确clientHeight的机会:

myDialog.addEventListener( "iron-overlay-opened", function ()
{
    this.querySelector( "custom-expand-component" ).init()
} )

init() 方法中,为私有变量设置正确的值:

var CEC = Object.create( HTMLElement.prototype )
CEC.createdCallback = function () {
    var that = this
    var startHeight
    var contentHeight 
    this.init = function () {
        if ( !contentHeight ) {
            contentHeight = this.clientHeight + "px"  //OK
            startHeight = this.getAttribute( "start-height" )
            opened = false                  
            this.style.height = startHeight
        }
    }
    document.getElementById( this.getAttribute( "trigger" ) ).onclick = toggle
    function toggle() {
        opened = !opened
        that.style.height = ( opened )? contentHeight : startHeight
    }
}
document.registerElement( "custom-expand-component", { prototype: CEC } )

CSS 过渡现在正在工作:

custom-expand-component {
    display: block ;
    overflow-y: scroll ;
    transition: height 0.5s ;
}