jQuery 语法:为 css 值使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5973440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:08:03  来源:igfitidea点击:

Syntax: Use variable for css value

jquerycssmathvar

提问by C_K

Trying to keep a box centered vertically within another box. I know there's css that can do this, but I'd rather use jquery, more reliable(?).

试图保持一个盒子在另一个盒子内垂直居中。我知道有 css 可以做到这一点,但我宁愿使用 jquery,更可靠(?)。

var textH = $(".Text").height();
var vertAlign = ((140 - textH)/2);

$(".Text").css({
    marginTop: 'vertAlign'
});

Not sure what detail I'm missing. The output should be half the available vertical space, in pixels.

不知道我错过了什么细节。输出应该是可用垂直空间的一半,以像素为单位。

EDIT

编辑

Originally, the text block was a span contained by a div. The div had a set height (140 px in this case), and the text block, the span, would be variable height based on how much text was in it. However, I need this text block to be editable. So I changed it to a text area. however, the behavior for the dimensions of the text area is awkward, and I had to set a static height and width to it. Now the height of this text block isn't variable, so there's no difference in height between it and it's parent with which to derive the margin-top spacing from. What should I do?

最初,文本块是一个 div 包含的跨度。div 有一个设定的高度(在这种情况下为 140 像素),文本块的高度将根据其中的文本数量而变化。但是,我需要这个文本块是可编辑的。所以我把它改成了一个文本区域。但是,文本区域尺寸的行为很尴尬,我不得不为其设置静态高度和宽度。现在这个文本块的高度不是可变的,所以它和它的父级之间的高度没有差异,用于从中导出边距顶部间距。我该怎么办?

回答by Arman P.

Remove quotes surrounding vertAlign

删除周围的引号 vertAlign

$(".Text").css('margin-top', vertAlign);

Try the above code. It must help you.

试试上面的代码。它必须帮助你。

回答by robx

optionally if you'd like to do more than one style:

如果你想做不止一种风格,可以选择:

var styles = {'margin-top':vertAlign,'property':100,'property':somevalue}
$(".Text").css(styles);

回答by Arjan

var textH = $(".Text").height();
var vertAlign = ((140 - textH)/2);
$(".Text").css({
        margin-top: vertAlign + 'px'
    });

You need to specify the unit, otherwise your browser won't be able to tell whether you want pixels or em or apples.Also you might want to do some range checking, you do not want vertAlignto be negative.

您需要指定单位,否则您的浏览器将无法判断您想要像素、em 还是苹果。此外,您可能想要进行一些范围检查,您不想vertAlign为负数。