我有一个固定的div,并使用css放在页面上。我有另一个div,它是动态生成的,并添加到页面中心的形式和位置。在文档上发生单击时添加此div。
问题是当我点击文档时,div动态添加到页面并正确定位但静态div位置变化。我只是不明白为什么会这样。 here is my code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).click(function (e) {
// Check for left button click
if (e.button == 0) {
$('form').append('<div id="dvfloat" class="float_div">Welcome</div>').center().fadeIn('slow');
}
});
jQuery.fn.center = function () {
this.css("position", "absolute");
this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
});
</script>
<style type="text/css">
.login_div {
background-color: Yellow;
margin-left: 50px;
position: absolute;
width: 100px;
}
.float_div {
background-color: Green;
width: 100px;
height:50px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="static_dv" class="login_div"> hi how r u ? </div>
</form>
</body>
</html>
请运行我的代码并查看效果。名为“static_dv”的静态div在我点击文档时重新定位,但我没有写任何代码来执行此操作。我希望静态div应该改变它的位置。什么是修复。感谢
答案 0 :(得分:1)
你的div在形式中,在你的js中你改变了位置FORM,所以所有内容都改变了
试试这个
var div = $('<div id="dvfloat" class="float_div">Welcome</div>');
$('FORM').append(div)
div.center().fadeIn('slow');
你需要设置div的位置,但是($ TAG).append($ someTag)的构造 - 返回$ TAG,所以你将中心位置设置为$ TAG
答案 1 :(得分:1)
你实际上并不是新创建的DIV的中心,而是整个形式,尝试这个小小的改变:
$('form').append('<div id="dvfloat" class="float_div">Welcome</div>').fadeIn('slow');
$('#dvfloat').center();
答案 2 :(得分:0)
使用此代码 您的“this”指的是表单,您正在更改表单的位置,因此无法正常工作。使用下面引用div的新代码
$(document).ready(function() {
$(document).click(function(e) {
// Check for left button click
if (e.button == 0) {
$('form').append('<div id="dvfloat" class="float_div">Welcome</div>').center().fadeIn('slow');
}
});
jQuery.fn.center = function() {
this.find('.float_div').css("position", "absolute");
this.find('.float_div').css("top", Math.max(0, (($(window).height() - this.find('.float_div').outerHeight()) / 2) + $(window).scrollTop()) + "px");
this.find('.float_div').css("left", Math.max(0, (($(window).width() - this.find('.float_div').outerWidth()) / 2) + $(window).scrollLeft()) + "px");
return this;
}
});