试着改变'属性

Trying to change 'margin-top' attribute

本文关键字:属性 改变      更新时间:2023-09-26

这就是我要做的:

$(function(){           
  $('div.item').css('margin-top',-(closest('img').height())/2+'px'); 
});

我要我的'<div class="item"'>得到style="margin-top:XXXXXX; top:50%"其中'XXXXXX' = (('div.item a img').height())/2

======================================================

EDIT:(已解决)对于感兴趣的人来说,最后的代码是:

<script type="text/javascript">
$(function(){
theWindow.resize(function() {
$('div.item').each(function(i){          
  $(this).css('top',(($(window).height())/2)-(($(this).first('img').height())/2)+'px'); 
});
}).trigger("resize");
});    
</script>

(我只用了top属性而不是top + margin-top)感谢您的帮助

我认为这可能是你需要的,特别是如果你有多个div.item

$('div.item').each(function(){
    var r = $(this).find('img').first().height();
    $(this).css('margin-top', r/2 + 'px'); 
}); 

编辑

你需要.find()img,然后选择.first()

示例:http://jsfiddle.net/jasongennaro/JNMhC/3/

据我所知,你正试图做这样的事情:

$(function(){           
  $('div.item').css('margin-top',-($('div.item').closest('img').height())/2+'px'); 
});

但是图像选择器取决于你的html配置。
如果你发布一些html标记,也许我可以提供一个更好的解决方案。