浏览代码

Disable background scroll if modal is open

If the modal is opened on top of scrollable content, allow scrolling
only for the opened modal, disabling the scrollable content's scroll.
When closing the modal, restore scrolling functionality and scrolling
position to modal's parent's scrollable content.
Sergiu Miclea 8 年之前
父节点
当前提交
4892975af0
共有 1 个文件被更改,包括 23 次插入0 次删除
  1. 23 0
      src/components/molecules/Modal/Modal.jsx

+ 23 - 0
src/components/molecules/Modal/Modal.jsx

@@ -56,6 +56,12 @@ class NewModal extends React.Component {
     setTimeout(this.positionModal, 100)
     setTimeout(this.positionModal, 100)
   }
   }
 
 
+  componentWillReceiveProps(newProps) {
+    if (this.props.isOpen === true && newProps.isOpen === false) {
+      this.handleModalClose()
+    }
+  }
+
   componentWillUpdate() {
   componentWillUpdate() {
     setTimeout(this.positionModal, 100)
     setTimeout(this.positionModal, 100)
   }
   }
@@ -68,6 +74,22 @@ class NewModal extends React.Component {
     setTimeout(this.positionModal, 100)
     setTimeout(this.positionModal, 100)
   }
   }
 
 
+  handleModalOpen() {
+    this.windowScrollY = window.scrollY
+    document.body.style.top = `${-this.windowScrollY}px`
+    document.body.style.position = 'fixed'
+    document.body.style.width = '100%'
+    document.body.style.height = '100%'
+  }
+
+  handleModalClose() {
+    document.body.style.top = ''
+    document.body.style.position = ''
+    document.body.style.width = ''
+    document.body.style.height = ''
+    window.scroll(0, this.windowScrollY)
+  }
+
   positionModal() {
   positionModal() {
     let pageNode = this.modalDiv && this.modalDiv.node.firstChild
     let pageNode = this.modalDiv && this.modalDiv.node.firstChild
     let contentNode = pageNode && pageNode.firstChild
     let contentNode = pageNode && pageNode.firstChild
@@ -145,6 +167,7 @@ class NewModal extends React.Component {
         contentLabel={this.props.contentLabel || this.props.title}
         contentLabel={this.props.contentLabel || this.props.title}
         style={modalStyle}
         style={modalStyle}
         onRequestClose={this.props.onRequestClose}
         onRequestClose={this.props.onRequestClose}
+        onAfterOpen={() => { this.handleModalOpen() }}
       >
       >
         {this.renderTitle()}
         {this.renderTitle()}
         {children}
         {children}