我已遵循此链接上的代码:Using jQuery to center a DIV on the screen我的 div 没有居中。有什么想法吗?
在我的 javascript 错误控制台中似乎没有错误。这是我的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="./Scripts/jquery-1.4.1.js" type="text/javascript">
(function ($) {
$.fn.extend({
center: function () {
return this.each(function () {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({ position: 'absolute', margin: 0, top: (top > 0 ? top : 0) + 'px', left: (left > 0 ? left : 0) + 'px' });
});
}
});
})(jQuery);
$('#login').center();
</script>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
</head>
<body bgcolor="#0066cc">
<form id="form1" runat="server">
<div>
<h1>Welcome to SeeUBook</h1>
</div>
<div id="login">
//some code
</div>
</form>
</body>
</html>
最佳答案
一旦元素位于 DOM 中(在 document.ready
上),您需要在元素上运行插件,如下所示:
$(function() {
$('#login').center();
});
...当前它在页面中找到 id="login"
元素之前运行,因此它没有居中任何内容。
关于javascript - 不能居中div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4533555/