-1

我不太擅长编程移动网络布局等。

我写了这个:

HTML:

<div id="title">...</div>

JavaScript

$("#title").css("margin-left", "7%");
$("#title").css("margin-right", "7%");

var i = screen.width * 0.018 + "px";          // It would be 24.588 at resolution of 1366
$("#title").css("margin-top", i);                // And i wanted to use 24.588px here 
$("#title").css("margin-bottom", i);         // and here.

Chrome 在左侧和右侧显示 div 边距,但不呈现顶部和底部 MARGINS ......

4

3 回答 3

4

您的所有margin_*属性不应该用下划线分隔,而是用-破折号分隔,如下所示:

$("#title").css("margin-left", "7%");
$("#title").css("margin-right", "7%");

var i = screen.width * 0.018 + "px";
$("#title").css("margin-top", i);
$("#title").css("margin-bottom", i);

jQuery 的.css()方法在以这种形式使用时,将 CSS 属性名称作为其第一个参数,并将要设置的值作为其第二个参数。

另一种更好的方法是将对象传递给.css()

var margin = screen.width * 0.018 + "px";

$('#title').css({
    marginLeft:   "7%",
    marginRight:  "7%",
    marginTop:    margin,
    marginBottom: margin
});

请注意,在这里您需要使用属性的驼峰式版本。

另外,为什么不使用百分比来表示顶部和底部边距,而不是在 JavaScript 中计算它们呢?

于 2013-10-26T17:38:53.347 回答
1

不需要任何下划线或破折号,您需要使用大写字母,例如:

$("#title").css("marginLeft", "7%");
于 2013-10-26T17:41:15.937 回答
0

这可能更简单。

function marge() {
    var sw = $(window).width() * 0.018 + "px";//get margin
    $("#title").css({margin: sw+' 7%'});//set margin tb lr
}
marge();//run initially
$(window).resize(function() { marge(); });//to adjust on resize of the window

第 2 行和第 3 行解决了这个问题,其余的允许它在需要时在调整窗口大小时再次运行该函数。

做了一个小提琴:http: //jsfiddle.net/filever10/z2HQL/

于 2013-10-26T18:20:35.750 回答