jquery - 不同屏幕上的 CSS margin-top 问题

标签 jquery css

这是我的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/

相关文章:

html - Twitter Bootstrap 的底部填充/边距问题

javascript - jQuery 选择器选择每个字母的第一个元素

javascript - 动画时换行的子元素

javascript - 如何使用 JQuery 搜索 JSON 字符串

jquery - 不以 ":"开头的自定义 jQuery 选择器

html - 如何在 rails 4 中将部分表单呈现为水平表单

JavaFX - StackedAreaChart 和方法 setLowerBound

javascript - Bootstrap - Jumbotron - 自动图像更改 - jQuery

css - 为什么我的 CSS 变量不起作用?

html - Bootstrap 3 水平导航添加 anchor