jQuery位置div位于页面中间 好的,所以我有一个div,我想把它放在页面的中间。 我已经走了这么远 $("#a").css('margin-top', '(document).height()/2 - ("#a").height()/2');

jQuery位置div位于页面中间 好的,所以我有一个div,我想把它放在页面的中间。 我已经走了这么远 $("#a").css('margin-top', '(document).height()/2 - ("#a").height()/2');,jquery,html,Jquery,Html,这是正确的吗?**不应该用引号括起来。此外,还需要使用$()术语。试试这个: $("#a").css('margin-top', $(document).height()/2 - $("#a").height()/2); 或者更好: var $a = $("#a"); $a.css('margin-top', $(document).height()/2 - $a.height()/2); 编辑:为了清楚起见,您不能将其置于引号中,因为它会尝试将边距顶部属性逐字设置为该字符串。这是不正确的。

这是正确的吗?

**不应该用引号括起来。此外,还需要使用
$()
术语。试试这个:

$("#a").css('margin-top', $(document).height()/2 - $("#a").height()/2);
或者更好:

var $a = $("#a");
$a.css('margin-top', $(document).height()/2 - $a.height()/2);
编辑:为了清楚起见,您不能将其置于引号中,因为它会尝试将边距顶部属性逐字设置为该字符串。这是不正确的。

我建议您使用

说明:设置匹配元素集中每个元素相对于文档的当前坐标


这一个对我有用&可能会有帮助:

$('html, body').animate(
   {
   scrollTop: $('#your_div_id').offset().top-200
   }, 1000);

更改“top-200”中的值200,以根据需要定位您的div。

是。。。它起作用了!谢谢我从来不知道这就像删除引号一样简单。
$('html, body').animate(
   {
   scrollTop: $('#your_div_id').offset().top-200
   }, 1000);