不能用var设置边距:JavaScript,CSS和jQuery

Can't set margins with var: JavaScript, CSS and jQuery

本文关键字:CSS jQuery JavaScript var 置边距 不能      更新时间:2023-09-26

我不太擅长编写移动网页布局等等。

我写过这个:

.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 边距,但不渲染顶部和底部边距...

所有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 中计算它们呢?

不需要

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

$("#title").css("marginLeft", "7%");

这可能更简单。

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/