添加关闭按钮以自动弹出窗口

时间:2013-10-01 23:46:45

标签: javascript jquery css

我正在尝试将自动弹出框添加到网站的主页。我使用了本网站上一个答案的代码,如下所示。弹出窗口工作正常,但你还可以添加一个关闭按钮/链接吗?在此先感谢您的帮助。

使用Javascript:

<script type="text/javascript">
function show_popup()
{
  document.getElementById('popup').style.display = 'block'; 
}

window.onload = show_popup;
</script>

CSS:

#popup
{
position:absolute;
z-index:99;
display:block;
top:200px;
left:50%;
width:567px;
height:420px; 
margin-left:-250px; 
}

和电话:

<div id="popup">pop up window</div>

3 个答案:

答案 0 :(得分:1)

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>‌    
<div id="popup">
<div id='popup-close'>Close</div>
pop up window
</div>

你的jQuery,

$(document).ready(function()
{
    $('#popup').show('fast'); // This will show the Pop Up in the Page Load
    $('#popup-close').click(function(e) // You are clicking the close button
    {
      $('#popup').hide('fast'); // Now the pop up is hided.
    });
});

答案 1 :(得分:0)

popup中添加另一个div,点按此按钮会激活此document.getElementById('popup').style.display = 'none';。您可以relatively将div定位到top, right足够简单。

答案 2 :(得分:0)

这是在弹出式div中使用第二个绝对div的简单方法。

很多方法可以改进它并添加更多东西。

function show_popup() {
  document.getElementById('popup').style.display = 'block'; 
}
window.onload = show_popup;
$('.popup-closer').click(function() {
	$('#popup').hide();
});
#popup {
  position: absolute;
  z-index: 99;
  display: block;
  top: 50%; left: 50%; /* if you want to center it do this.. */
  transform: translate(-50%, -50%); /* ..and this */
  width:150px;
  height:225px; 
  color: white;
  background-color: black;
}
.popup-closer {
  position:absolute;
  top: 5px;
  right: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: red;
  border-radius: 20px;
  padding: 5px;
  cursor: pointer;
}
.popup-closer:hover {
  background-color: white;
}




html, body {
  margin: 0; padding: 0;
}
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="popup">
  pop up window
  <div class="popup-closer"><i class="fa fa-close"></i></div>
</div>

如果您希望每个会话或每天每个用户只显示一次,请查看会话和本地存储。弹出窗口可以首先检查他们的会话存储,如果他们已经在此会话/今天/等已经提供通知,如果是这样,则阻止他们显示第二个+时间。如果您在整个网站范围内拥有代码并且不希望每次加载页面时都弹出相同的交易。

此外,可能想要制作#popup position: fixed;,因此当用户滚动页面时,弹出窗口会一直保留,直到他们确认并关闭它。

<强>拨弄

https://jsfiddle.net/Hastig/au3xm1oy/

和更多想法的额外小提琴

https://jsfiddle.net/Hastig/au3xm1oy/2/