jq弹窗(获取页面宽高,滚轮高度,始终居中)

jq写一个弹窗,效果如上图所示,

点击按钮弹窗弹出,右上角关闭。

弹窗始终显示在页面中间,无论放大缩小窗口,滚轮滚动。

代码如下:

html:

<br><br><br><br>
<button>弹出</button>
<div id="tanchuang">
	<span id="close">×</span>
</div>
<br><br><br>

 js:

$(function(){
	//定义页面宽度,页面高度,弹窗位置left,弹窗位置top,滚动条高度
	var screenWidth,screenHeight,tcleft,tctop,scrollTop;
	//计算弹窗位置的函数
	tanLocation();
	//按钮添加点击事件,调用方法show(),使弹窗div出现
	$('button').click(function(){
		$('#tanchuang').show();
	})
	//关闭按钮添加点击事件,调用方法hide(),使弹窗div消失
	$('#close').click(function(){
		$('#tanchuang').hide();
	})
	//窗口对象添加resize() 当浏览器窗口大小改变时执行。
	$(window).resize(function(){
		tanLocation();
	})
	//文档对象添加scroll() 当滚轮高度变化时执行
	$(document).scroll(function(){
		tanLocation();
	})
})
//计算弹窗位置的函数
function tanLocation(){
	//获取页面宽度
	screenWidth = $(window).width();
	//获取页面高度
	screenHeight = $(window).height();
	//计算left值
	tcleft = (screenWidth-100)/2;
	//计算top值
	tctop = (screenHeight-100)/2;
	//获取滚轮高度
	scrollTop = $(document).scrollTop();
	//弹窗的位置样式改变
	$('#tanchuang').css({'top':tctop+scrollTop,'left':tcleft});
}

猜你喜欢

转载自www.cnblogs.com/SSs1995/p/9210533.html