繁体   English   中英

如何将offset .top应用于div的高度?

[英]How to apply the offset .top to the height of a div?

在此博客上,我想编辑#content div的高度,并将其高度设置为:x.top px(文章:last-child),以便垂直重复的背景。

http://manutdstream.tumblr.com/

我试图这样做:

$(document).ready(function(){
x=$("article:last-child").offset();
$('#content').css('height' : 'x.top px');

});

我认为问题出在.css()中,当我运行它以警告x.top时,它运行正常。

您的变量被视为字符串,将其放在引号之外,然后使用+将其添加到字符串中:

 $(document).ready(function(){
    var x = $("article:last-child").offset();
    $('#content').css('height' : x.top + 'px');
  });

.css()的语法不正确,应为

  $('#content').css('height', x.top + 'px');

小提琴的例子:

http://jsfiddle.net/jessikwa/5vnbLr91/

如果您只是设置高度,则无需理会css 像素是height功能的默认单位:

$(document).ready(function(){
  var lastArticle = $("article:last-child");
  $('#content').height(lastArticle.offset().top);
});

不建议您选择,但我建议即使是简单的事情也不要使用诸如x类的变量-除非您实际上是指 x (例如,坐标空间)。 代码已经很难阅读,但是好名字可以使代码变得更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM