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

标签 javascript jquery html css

我这里有一个简单的代码,可以将工具提示的上边距提高它的高度。

$("#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/

相关文章:

javascript - 谷歌地图 API : cannot click on clickable polygon behind datalayer

javascript - 使用带有变换属性的缩放时定位 sibling

javascript防止鼠标中键在新标签页中打开链接

javascript - NodeJS http 模块 : what is requestListener?

javascript - HTML onClick 不适用于 Windows Phone

javascript - javascript/jquery 的标准调试方式

javascript - 使用无限滚动在单个页面上显示多个谷歌广告

php - 使用 JavaScript 维护动态 MySQL 表

html - 在悬停时添加边框时使菜单项对齐

javascript - 正则表达式 : replace character