如何根据元素的高度更改元素的上边距?

时间:2013-09-07 16:26:09

标签: javascript jquery html css

我在这里有一个简单的代码,用它的高度来提高工具提示的上边距。

$("#tooltip").css({'marginTop':'-' + $("#tooltip").height});

我正在使用带有UI 1.9.2的jQuery 1.9.1,并且我不确定为什么这不起作用。

工具提示是元素,margintop应设置为- + tooltip.height

示例
tooltip.height = 50px, margin-top:-50px;

有人可以指出我的错误吗? 感谢

3 个答案:

答案 0 :(得分:2)

尝试以下方法:

$("#tooltip").css("margin-top", function() { 
    return -1 * $(this).outerHeight() // <== Multiplies outerHeight() by -1 and returns the result
});

在这种情况下,如果$.css()收到一个数字,它会自动转换为带有'px'的字符串。如果它收到一个字符串,则表示该值已完成,应按原样设置。

以下内容也会起作用:

// Passing in a number
$("#tooltip").css({'marginTop':  - $("#tooltip").outerHeight()});
$("#tooltip").css({'marginTop':  -1 * $("#tooltip").outerHeight()});
$("#tooltip").css('marginTop',  - $("#tooltip").outerHeight());
$("#tooltip").css('marginTop',  -1 * $("#tooltip").outerHeight());

// Passing in a string with units specified
$("#tooltip").css({'marginTop':  '-' + $("#tooltip").outerHeight() + 'px'});
$("#tooltip").css('marginTop',  '-' + $("#tooltip").outerHeight() + 'px');

虽然失败了,因为结果字符串"-20"是marginTop的无效css值:

$("#tooltip").css({'marginTop':  '-' + $("#tooltip").outerHeight()});

如果要使用百分比或em设置值,则字符串形式非常有用:

$("#tooltip").css({'marginTop':  "2em"});
$("#tooltip").css({'marginTop':  "10%"});

答案 1 :(得分:0)

$("#tooltip").css("margin-top", function() { return $(this).outerHeight() });

答案 2 :(得分:0)

$("#tooltip").css({ marginTop: - $("#tooltip").outerHeight() + 'px' });
相关问题