使href转到div而不是页面

时间:2016-07-11 18:50:17

标签: javascript jquery html css

基本上href会转到#popups div并在codepen上生成一个弹出窗口。

然而,当我将该代码粘贴到页面中时。它转到一个链接。无论如何只有在单击A href时触发弹出事件?我试过这个 编辑:我只想触发div弹出窗口。我不希望href转到新页面。

  <a href="#popups" onclick="">Test</a>

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  transition: opacity 200ms;
  visibility: hidden;
  opacity: 0;
}
.overlay.light {
  background: rgba(255, 255, 255, 0.5);
}
.overlay .cancel {
  position: absolute;
  width: 100%;
  height: 100%;
  cursor: default;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}
.popup {
  margin: 75px auto;
  padding: 20px;
  background: #fff;
  border: 1px solid #666;
  width: 300px;
  box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
  position: relative;
}
.light .popup {
  border-color: #aaa;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.25);
}
.popup h2 {
  margin-top: 0;
  color: #666;
  font-family: "Trebuchet MS", Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 20px;
  right: 20px;
  opacity: 0.8;
  transition: all 200ms;
  font-size: 24px;
  font-weight: bold;
  text-decoration: none;
  color: #666;
}
.popup .close:hover {
  opacity: 1;
}
.popup #content {
  max-height: 400px;
  overflow: auto;
}
.popup p {
  margin: 0 0 1em;
}
.popup p:last-child {
  margin: 0;
}
<a href="#popups" onclick="">Test</a>

<div id="popups" class="overlay">
  <div class="popup">
    <h2>Info box</h2>
    <a class="close" href="#">&times;</a>
    <div id="content">
      Old Content
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:5)

试试这个:

$('a').on('click',function(e){
    e.preventDefault();
});