我这里有一个简单的代码,可通过其高度来提高工具提示的顶部边距。

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


我正在将jQuery 1.9.1与UI 1.9.2一起使用,并且不确定为什么这不起作用。

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


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

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

最佳答案

请尝试以下方法:

$("#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%"});

10-07 14:43
查看更多