Javascript 如何使用样式标记在js中使用变量

Javascript 如何使用样式标记在js中使用变量,javascript,jquery,html,css,Javascript,Jquery,Html,Css,如何在样式标记中使用javascript变量? 我尝试使用jQuery: var height = $('.replyComment').height(); $('div.replyComment').append('<style>div.replyComment:before{content: ""; border-left: 1px solid #e1e1e1;position:absolute; left:38px; top:-20px; height:'+ height +'

如何在样式标记中使用javascript变量? 我尝试使用jQuery:

var height = $('.replyComment').height();
$('div.replyComment').append('<style>div.replyComment:before{content: ""; border-left: 1px solid #e1e1e1;position:absolute; left:38px; top:-20px; height:'+ height +';}</style>');
var height=$('.replyComment').height();
$('div.replyComment').append('div.replyComment:在{content:;左边框:1px实心#e1e1e1e1;位置:绝对;左:38px;顶部:-20px;高度:'+height+';}');

那么我错在哪里呢?要在div中指定div的高度,我必须做什么:在使用height变量之前?

尝试将其附加到
head

$('head').append('<style>div.replyComment:before{content: ""; border-left: 1px solid #e1e1e1;position:absolute; left:38px; top:-20px; height:'+ height +'px;}</style>');
$('head').append('div.replyComment:before{content:;边框左侧:1px实心#e1e1e1e1e1;位置:绝对;左侧:38px;顶部:-20px;高度:'+height+'px;}');

确保您必须将
px
添加到高度。

您可以使用jQuery的CSS功能

css({“propertyname”:“value”,“propertyname”:“value”,…})

就像这样:

var height = jQuery('.replyComment').height();

jQuery('div.replyComment:before').css({
  "content":"",
  "border-left":"1px solid #e1e1e1",
  "position":"absolute",
  "left":"38px",
  "top":"-20px",
  "height": height
});
更多信息:,

试试这个

jQuery('div.replyComment').css('height', height);

div.replyComment:before{
    content: ""; 
    border-left: 1px solid #e1e1e1; 
    position:absolute; 
    left:38px; 
    top:-20px; 
}
将css添加到样式表中,然后在需要时专门针对div高度。

从中,您可以看到如何使用
高度()
,不仅可以获得元素的高度,还可以设置它。只需将新高度作为参数传递:
.height(value)

除此之外。设置内联css样式不是一个好的做法。我宁愿使用jQuery中的函数和函数来更改HTML元素的样式

对于您的示例,它将如下所示:

css

javascript

$('div.replyComment').addClass('styles-to-add');
然后,您可以单独设置任何元素的高度,如:

var height = $('.replyComment').height();
$('div.replyComment:before').height(height);

您可以使用
css()
,来应用cssMain问题-您需要添加'px':高度:'+height+'px;。。。等css需要度量单位,jQuery height()只返回数字。
var height = $('.replyComment').height();
$('div.replyComment:before').height(height);