2012-01-04 86 views
0

我现在看到我是复制粘贴错误的文本/问题,根本没有意义!对不起!我在我的代码中发现错误。这是一个工作版本:每个在jquery后追加

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title></title> 
<style type="text/css"> 
body{ 
margin:0; 
} 
#gallery{ 
width:100%; 
height:100%; 
position:fixed; 
left:0; 
top:0; 
background:#000; 
opacity:0.9; 
} 
.child{ 
width:auto; 
height:auto; 
position:fixed; 
left:0; 
top:0; 
} 
</style> 
</head> 
<body> 
<div id="click_me">click me</div> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> 
<script> 
$(document).ready(function() { 
$('#click_me').click(function(){ 
$('body').append('<div id="gallery"></div><div class="child" style="width:300px;height:600px;background:#0F0"></div><div class="child" style="width:500px;height:400px;background:#C60"></div><div class="child" style="width:600px;height:200px;background:#390"></div>'); 
    height_of_window = $('#gallery').height(); 
    width_of_window = $('#gallery').width(); 
    max_height = height_of_window - 100; 
    max_width = width_of_window - 100; 
    $('.child').each(function() { 
     var $this = $(this); 
     height_of_child = $this.height(); 
     width_of_child = $this.width(); 
     if (width_of_child >= max_width) { 
     $this.css({ 
      'max-width': max_width + 'px' 
     }) 
     } 
     if (height_of_child >= max_height) { 
     $this.css({ 
      'max-height': max_height + 'px' 
     }) 
     } 
     margin_top = (height_of_window - $this.height())/2; 
     margin_left = (width_of_window - $this.width())/2; 
     $this.css({ 
     'margin-top': margin_top + 'px', 
     'margin-left': margin_left + 'px' 
     }) 
    }); // end click 
    }); // end each 
}); // end document redy 
</script> 
</body> 
</html> 
+0

问题是什么? – 2012-01-04 10:48:09

+0

将更好地解释BRB – Hakan 2012-01-04 10:57:59

回答

0

你还没有告诉我们是什么问题,但:

你说,代码工作(如果是的话,它不会是可靠的;见下)如果你把标记放在HTML中,但不是如果你使用代码追加标记。你引用的代码不会有问题,因为它清楚地表明,你要追加,然后做了“图像配”的元素的搜索,但你需要之前,确保你做追加你运行其他代码,并且一旦body标签准备好将其附加到它后,就需要执行这些操作。请确保您的脚本处于最后,正好在关闭</body>标记之后(或之前),或者使用jQuery ready函数(或其shortcut)。

另外:

jQuery的css功能不支持简写属性,虽然他们在某些浏览器。每the docs

不支持速记CSS属性(例如页边距,背景,边框)。例如,如果要检索渲染边距,请使用:$(elem).css('marginTop')$(elem).css('marginRight'),依此类推。

所以这行:

$(this).css({'margin':margin_top+'px 0 0 '+ margin_left +'px'}) 

应该

$(this).css({ 
    marginTop: margin_top + 'px', 
    marginLeft: margin_left + 'px', 
    marginRight: "0px", 
    marginBottom: "0px" 
}); 

另外,注意每次你做$(this),它需要多个函数调用和内存分配。最好不要不必要地重复它;虽然它通常是无害的,但它会造成不必要的记忆流失。只需在函数的开始放置var $this = $(this);,然后在整个(或其他任何你想要调用它的地方)使用$this。 (其中一个疑问:请记住this在每个函数中都有[潜在]更改,因此如果您设置了事件处理程序,请勿使用外部函数的$this,因为这意味着要使用事件处理程序的版本。)

+0

感谢指出“简写属性”只在某些浏览器工作!不知道... – Hakan 2012-01-04 11:45:21

0

你需要用与

$(function() { 

    }); 

这段代码,使其运行jQuery代码之前先加载体。还要确保max_width和max_height的设置与此代码中的设置不同。