好的,所以我有一个div,我想把它放在页面中间.我到目前为止
$("#a").css('margin-top', '(document).height()/2 - ("#a").height()/2');
Run Code Online (Sandbox Code Playgroud)
它是否正确?
**它不应该在引号中.此外,您需要使用$()术语.试试这个:
$("#a").css('margin-top', $(document).height()/2 - $("#a").height()/2);
Run Code Online (Sandbox Code Playgroud)
甚至更好:
var $a = $("#a");
$a.css('margin-top', $(document).height()/2 - $a.height()/2);
Run Code Online (Sandbox Code Playgroud)
编辑:为了清楚,你不能把它放在引号中,因为它会尝试将margin-top属性字面设置为该字符串.这是不正确的.
我建议你用.offset().
描述:设置相对于文档的匹配元素集中每个元素的当前坐标.
$("#a").offset({
top: $(document).height()/2 - $("#a").height()/2,
left: $(document).width()/2 - $("#a").width()/2
})
Run Code Online (Sandbox Code Playgroud)