在一些頁面中,咱們總會遇到一些彈窗不居中的時候,還要根據瀏覽器的大小來調整彈窗的彈出位置,javascript
以前我也遇到這樣的問題,如今我把我知道的呈現給你們css
css樣式html
.windowBox{java
width:500px;jquery
}瀏覽器
.mid-tanBox{ide
position: fixed; top: 50%; left: 50%; margin-left: -250px; background: #fff; border:1px solid red; display:nonehtm
}ip
html代碼input
<div class='windowBox'>
<div class ="mid-tanBox"></div>
<div class="jclick">彈窗</div>
</div>
jQuery代碼自動:
$(".jclick").click(function(i){
var height = $(".mid-tanBox").height();
var eheight = height/2;
$(".mid-tanBox").eq(i).css("margin-top","-eheight");
})
額外:-JS
<style>
*{margin:0px;padding:0px}
.all-tanch{ background:blue; position: fixed; display:none; color: #fff; padding:50px;}
.wraper{ width:600px; background:#333; color: #fff; position:relative; margin:30px;}
.sonone{background:red; display:none;position:absolute;}
</style>
<Script type="text/javascript" src="jquery.js"></script>
<!--針對瀏覽器窗口垂直居中-->
<Script type="text/javascript">
function popup(poName){
var scrollHeight = $(document).scrollTop();//獲取當前窗口距離頁面頂部高度
var windowHeight = $(window).height();//獲取當前窗口高度
var windowWidth = $(window).width();//獲取當前窗口寬度
var popupHeight = popupName.height();//獲取彈出層高度
var popupWeight = popupName.width();//獲取彈出層寬度
alert(windowHeight);
posiTop = (windowHeight)/2;
posiLeft = (windowWidth)/2;
poName.css({"left": posiLeft + "px","top":posiTop + "px","display":"block"});//設置position
}
$(function(){
$(".clickme01").click(function(){
popup($(".all-tanch"));
$(".wraper").hide();
});
});
</script>
<!--針對當前層 窗口垂直居中-->
<Script type="text/javascript">
function middleModle(selectorName){ //參數: 定義的class或ID,,其餘
var fatherHeight = $(".wraper").height();//獲取當前窗口高度
var fatherWidth = $(".wraper").width();//獲取當前窗口寬度
var tanHeight = selectorName.height();//獲取彈出層高度
var tanWeight = selectorName.width();//獲取彈出層寬度
var poTop = (fatherHeight - tanHeight)/2;
var poLeft = (fatherWidth - tanWeight)/2;
selectorName.css({"left": poLeft + "px", "top":poTop + "px", "display":"block"});//設置position位置
}
$(function(){
$(".clickme02").click(function(){
$(".wraper").show();
middleModle($(".sonone"));
});
});
</script>
<input class="clickme01" type="button" value="針對瀏覽器窗口垂直居中"/>
<input class="clickme02" type="button" value="針對當前窗口垂直居中"/>
<div class="all-tanch">
整個彈窗
</div>
<div class="wraper">
我是父級層--
<div class="sonone">你們好,我是彈窗,沒有樣式本身湊合着看吧!!!!</div>
</div>