当模态关闭时,页面滚动到顶部

时间:2015-09-25 17:53:45

标签: html css3 modal-dialog

我已经实现了一个模态,但是当模态关闭时,我不希望页面滚动到顶部。它会自动执行此操作。是否有一个代码管理我失踪的代码?谢谢你的帮助!

HTML

<a href="#target-content" id="button">Open A Modal</a>

<div id="target-content">
  <a href="#" class="close"></a>
  <div id="target-inner">
    <h2>Modal Heading</h2>
    <p>Modal Content</p>
  </div>
</div>

CSS

#target-content {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  pointer-events: none;
  opacity: 0;
  -webkit-transition: opacity 200ms;
  transition: opacity 200ms;
}

#target-content:target {
  pointer-events: all;
  opacity: 1;
}

#target-content #target-inner {
  position: absolute;
  display: block;
  padding: 48px;
  line-height: 1.8;
  width: 70%;
  top: 50%;
  left: 50%;
  -webkit-transform: translateX(-50%) translateY(-50%);
  -ms-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
  box-shadow: 0px 12px 24px rgba(0, 0, 0, 0.2);
  background: white;
  color: #34495E;
}

#target-content #target-inner h2 { margin-top: 0; }

#target-content #target-inner code { font-weight: bold; }

#target-content a.close {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #34495E;
  opacity: 0.5;
  -webkit-transition: opacity 200ms;
  transition: opacity 200ms;
}

#target-content a.close:hover { opacity: 0.4; }

2 个答案:

答案 0 :(得分:1)

#属性中的href会将您的信息页发送到顶部。

<a href="#" class="close"></a> <!-- moves scroll position to top of page -->

一种解决方案是将#替换为您希望页面进入或停留的特定ID。

试试这个:

<a href="#target-content" class="close"></a>

在此处阅读有关超链接和主题标签的详情:What is href="#" and why is it used?

答案 1 :(得分:1)

正如Michael_B所说,你的href标签中的“#”会将页面发送到顶部。作为将你的href设置为id的替代方法(即“href ='#target'”) - 你可以使用类似这样的东西来阻止任何事情发生:

href="javascript:void(0);"

这将解决您的问题。

相关问题