我这里有一个简单的代码,可以将工具提示的上边距提高它的高度。
$("#tooltip").css({'marginTop':'-' + $("#tooltip").height});
我正在使用 jQuery 1.9.1 和 UI 1.9.2,我不确定为什么这不起作用。
tooltip是元素,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%"});
关于javascript - 如何根据元素的高度更改元素的上边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675412/