这是我的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将是我的类页面标题的页边距顶值?解决这个问题的诀窍是什么?谢谢。
发布于 2015-11-17 19:52:31
您的类名是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");
}
}每次窗口大小改变时都会调用witch:
$(window).resize(function () {
fixMargin();
});请参阅工作小提琴:http://jsfiddle.net/avqoran9/
编辑2
<h1 class="page-title" style="margin-top: 7%">My Header</h1>小提琴:http://jsfiddle.net/zeLdapnx/
发布于 2015-11-17 20:17:35
好的,假设最大上边距为220,最小上边距为100,那么我们的差值为120
假设最小高度为600,最大高度为900
这意味着高度的每个像素增加0.4个像素的上边距。
因此,我们有以下函数:
function fixMargin() {
height = jQuery(window).height();
var minMargin = 100;
var maxMargin = 220;
var differenceMargin = maxMargin - minMargin;
var minHeight = 600;
var maxHeight = 900;
var calc = maxHeight - minHeight ;
var adjuster = differenceMargin/calc;
var differenceH = height - minHeight ;
var marginTop = math.round(differenceH * adjuster);
jQuery(".page-title").css("margin-top", marginTop);
}我要强调的是,这还没有经过测试,但我认为已经很接近了
https://stackoverflow.com/questions/33756137
复制相似问题