2015-09-18 44 views
1

如何在樣式標記中使用javascript變量? 我試着用jQuery:如何在js中使用樣式標記中的變量

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>'); 

那麼我錯在哪裏?我需要做什麼來分配div的高度:在使用高度變量之前?

+0

你可以使用'css()',應用css –

+0

主要問題 - 你需要添加'px':height:'+ height +'px; ... etc ... css需要度量單位,jQuery height()返回數字。 – sinisake

回答

2

嘗試將其附加到head

$('head').append('<style>div.replyComment:before{content: ""; border-left: 1px solid #e1e1e1;position:absolute; left:38px; top:-20px; height:'+ height +'px;}</style>'); 

確保您必須將px添加到高度。

0

您可以使用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 DocsW3Schools

0

試試這個。

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

div.replyComment:before{ 
    content: ""; 
    border-left: 1px solid #e1e1e1; 
    position:absolute; 
    left:38px; 
    top:-20px; 
} 

將css添加到樣式表中,然後在需要時專門定位div高度。

0

jQuery documentation你可以看到你如何使用height(),不僅得到元素高度,但設置它。只需通過新的高度作爲參數:.height(value)

除此之外。設置inline css樣式不是一個好習慣。我寧願使用jQuery的jQuery.addClass()jQuery.removeClass()函數來更改HTML元素的樣式。

對於你的榜樣會是這個樣子:

CSS

.styles-to-add:before{ 
    content: ""; 
    border-left: 1px solid #e1e1e1; 
    position: absolute; 
    left: 38px; 
    top: -20px; 
} 

的JavaScript

$('div.replyComment').addClass('styles-to-add'); 

再獨立,你可以設置像任何元素的高度:

var height = $('.replyComment').height(); 
$('div.replyComment:before').height(height); 
相關問題