简体   繁体   English

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

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

On this blog I want to edit the height of the #content div and make it height: x.top px (of the article:last-child) so that the background which is repeating itself vertically. 在此博客上,我想编辑#content div的高度,并将其高度设置为:x.top px(文章:last-child),以便垂直重复的背景。

http://manutdstream.tumblr.com/ http://manutdstream.tumblr.com/

I tried to do this: 我试图这样做:

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

}); });

I think the problem is in the .css() as when I ran it to alert the x.top it went fine. 我认为问题出在.css()中,当我运行它以警告x.top时,它运行正常。

Your variable is being treated as a string, place it outside the quotes and add it to the string with a +: 您的变量被视为字符串,将其放在引号之外,然后使用+将其添加到字符串中:

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

The syntax for .css() is incorrect, should be .css()的语法不正确,应为

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

Fiddle example: 小提琴的例子:

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

If you're just setting the height, no need to bother with css . 如果您只是设置高度,则无需理会css Pixels is the default unit for the height function: 像素是height功能的默认单位:

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

Not to nit-pick, but I'd recommend against using variables named something like x even for simple things -- unless you actually mean x (for example, coordinate spaces). 不建议您选择,但我建议即使是简单的事情也不要使用诸如x类的变量-除非您实际上是指 x (例如,坐标空间)。 Code is already hard to read, but good names can make it easier. 代码已经很难阅读,但是好名字可以使代码变得更容易。

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

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