偶实现的代码
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title></title>
<link rel="stylesheet" href="base.css" />
<script type="text/javascript" src="jquery-1.10.1.min.js" ></script>
</head>
<body>
<div style="height:10000px;"></div>
<style>.fix-center{ height:120px; width:219px; display:none; position:fixed; }</style>
<div id="fixCenter" class="fix-center">
<img src="fixCenter.jpg" width="219" height="120" usemap="#fixCenterMap">
<map name="fixCenterMap" id="fixCenterMap">
<area shape="rect" coords="175,0,219,30" href="javascript:void(0);" id="closeFixCenter" />
<area shape="rect" coords="0,30,219,94" href ="###1" target="_blank" />
<area shape="rect" coords="0,94,219,120" href ="###2" target="_blank" />
</map>
</div>
<script>
$(function(){
fixCenter();
});
function fixCenter(){
var fid = $('#fixCenter');
var h = $(window).height();
var w = $(window).width();
var l = (w/2) - parseInt(fid.css('width')) / 2;
var t = (h/2) - parseInt(fid.css('height')) / 2;
fid.css({'left': (l) + 'px', 'top': (t) + 'px' }).fadeIn(600);
$('#closeFixCenter').click(function(){
fid.fadeOut(600).delay(20000).fadeIn(600);
});
$(window).resize(function(){
h = $(window).height();
w = $(window).width();
l = (w/2) - parseInt(fid.css('width')) / 2;
t = (h/2) - parseInt(fid.css('height')) / 2;
fid.css({'left':(l) + 'px', 'top': (t) + 'px' });
});
}
</script>
</body>
</html>
结果群友(小硕)实现更短的代码:
function fixCenter(){
var fid = $('#fixCenter');
var h = $(window).height();
var w = $(window).width();
var l = (w/2) - parseInt(fid.width()) / 2;
var t = (h/2) - parseInt(fid.height()) / 2;
fid.css({'left': (l) + 'px', 'top': (t) + 'px' }).fadeIn(600);
$('#closeFixCenter').click(function(){
fid.fadeOut(600).delay(20000).fadeIn(600);
});
$(window).resize(function(){
h = $(window).height();
w = $(window).width();
l = (w/2) - parseInt(fid.width()) / 2;
t = (h/2) - parseInt(fid.height()) / 2;
fid.css({'left':(l) + 'px', 'top': (t) + 'px' });
});
}
效果图:
居中固定元素
本文介绍了一种使用JavaScript和jQuery实现页面元素居中的方法,并通过调整窗口大小保持元素位置不变。

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



