[英]How to use variable in js using style tag
如何在樣式標簽中使用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>');
那我在哪里錯了? 在使用height變量之前,我該怎么做才能在div中分配div的高度?
嘗試將其附加到head
。
$('head').append('<style>div.replyComment:before{content: ""; border-left: 1px solid #e1e1e1;position:absolute; left:38px; top:-20px; height:'+ height +'px;}</style>');
確保必須將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 Docs , W3Schools
試試這個吧。
jQuery('div.replyComment').css('height', height);
div.replyComment:before{
content: "";
border-left: 1px solid #e1e1e1;
position:absolute;
left:38px;
top:-20px;
}
將CSS添加到樣式表中,然后在需要時專門指定div高度。
從jQuery文檔中,您可以看到如何使用height()
,不僅可以獲取元素的高度 ,還可以對其進行設置。 只需將新高度作為參數傳遞: .height(value)
除此之外。 設置內聯 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.