这是我的javascript代码:
height = jQuery(window).height();
if (height < 700) {
jQuery(".page-title").css("margin-top", "100px");
} else if (height >= 700 && height < 800 ) {
jQuery(".page-title").css("margin-top", "160px");
}else{
jQuery(".page-title").css("margin-top", "220px");
}
这是html部分
<h1 class="page-title">My Header</h1>
我想要实现的是以某种方式按比例显示边距顶部。例如:我怎么知道 window.height = 890 这将是我类(class) page-title 的 margin-top 值?解决这个问题的诀窍是什么?谢谢。
最佳答案
您的类名是page-title
,而不是.page-title
。因此,您必须将 HTML 代码更改为:
<h1 class="page-title">My Header</h1>
点只是类的标识符。
编辑: 更正后,您的代码运行良好。代码在页面加载后仅执行一次。我想你想在每次窗口大小改变时调整它。所以我创建了一个函数:
function fixMargin() {
height = jQuery(window).height();
if (height < 700) {
jQuery(".page-title").css("margin-top", "100px");
} else if (height >= 700 && height < 800) {
jQuery(".page-title").css("margin-top", "160px");
} else {
jQuery(".page-title").css("margin-top", "220px");
}
}
每次窗口大小改变时都会调用女巫:
$(window).resize(function () {
fixMargin();
});
查看工作 fiddle :http://jsfiddle.net/avqoran9/
编辑2
<h1 class="page-title" style="margin-top: 7%">My Header</h1>
fiddle :http://jsfiddle.net/zeLdapnx/
关于jquery - 不同屏幕上的 CSS margin-top 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756137/