function center(obj){
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(obj).height();
var popupWidth = $(obj).width();
$(obj).css({
"position": "absolute",
"top": (windowHeight-popupHeight)/2+$(document).scrollTop(),
"left": (windowWidth-popupWidth)/2
});
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(obj).height();
var popupWidth = $(obj).width();
$(obj).css({
"position": "absolute",
"top": (windowHeight-popupHeight)/2+$(document).scrollTop(),
"left": (windowWidth-popupWidth)/2
});
}
//滚动的时候自动居中
$(window).scroll(function(){
center(obj);
});
//窗口变化自动居中
$(window).resize(function(){
center(obj);
});
//按回车提交
$(document).keydown(function(e){
if(e.keyCode ==13){
//要调用的方法
}
});
本文介绍了一种使用JavaScript实现网页弹窗或其他元素在页面中自动居中的方法,并确保在窗口调整大小或滚动时仍保持居中状态。此外,还展示了如何监听键盘事件以响应特定按键操作。
487

被折叠的 条评论
为什么被折叠?



