Jquery/Javascript是否需要DOM中的元素才能使用.css()?

Jquery/Javascript是否需要DOM中的元素才能使用.css()?,javascript,jquery,dom,Javascript,Jquery,Dom,这段代码是有效的,我试图计算一个div中的行数。也就是说,在我将这个元素添加到DOM中之前,我无法获得行高 最初我计划根本不添加它,因为我只使用它来计算DIV中的行数 在我添加它之前,它没有高度是有道理的,我只是想知道我是否做了正确的事情,或者是否有一种方法可以在不首先将其添加到DOM的情况下获得行高度。是的,它是。但是如果页面上有jQuery,为什么不使用它呢 if(typeof this.description === 'undefined') {alert('No Description

这段代码是有效的,我试图计算一个div中的行数。也就是说,在我将这个元素添加到DOM中之前,我无法获得行高

最初我计划根本不添加它,因为我只使用它来计算DIV中的行数


在我添加它之前,它没有高度是有道理的,我只是想知道我是否做了正确的事情,或者是否有一种方法可以在不首先将其添加到DOM的情况下获得行高度。

是的,它是。但是如果页面上有jQuery,为什么不使用它呢

if(typeof this.description === 'undefined') {alert('No Description Set!'); return false;}

var tempDiv = document.createElement('div'); //create a div outside of the DOM
tempDiv.className = 'descriptionColumn formBox contentRow'; //make sure and use the 
                    //same/equivlent class(s) to ensure accuracy

tempDiv.innerHTML = this.description; //insert the text

document.body.appendChild(tempDiv); //render div

lineHeight = parseInt($(tempDiv).css('line-height')); //get the line-height (make sure this is specified in CSS!)
                                                      //also we use Jquery here to handle any vender inconsistencies,
divHeight = tempDiv.clientHeight;  //get the div height

tempDiv.parentNode.removeChild(tempDiv); //clean up, delete div
delete tempDiv;

return divHeight/lineHeight;  //divide the height by the line-height and return
var$div=$(“”{
类:“descriptionColumn formBox contentRow”,
文字:“说明”,
css:{
位置:'绝对',
左:'-99999像素'
}
}).prependTo('body');//元素在此步骤中对用户不可见
//你的计算
$div.remove();

浏览器的渲染/布局决策由浏览器2条件决定:

1) 插入新元素

2) 某些元素的样式已更改

3) 有时在调整窗口大小时

因此,在元素进入DOM树之前,浏览器不会为其提供与布局相关的样式

考虑以下代码:

var $div = $('<div/>', {
    class: 'descriptionColumn formBox contentRow',
    text: 'Description',
    css: {
        position: 'absolute',
        left: '-99999px'
    }
}).prependTo('body'); // element wouldn't be visible for user on this step
//your calculations
$div.remove();
为什么?? 因为window.getComputedStyle()返回DOM(浏览器)中实际存在的CSS样式。 现在,

为什么?? 因为渲染引擎决定了CSS属性

//一个明白了

document.body.appendChild(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints rgb(somevalue)

是的,答案是肯定的。请始终将div的位置放在屏幕外进行测试。非常好,谢谢大家!仅当元素插入DOM时,浏览器才会呈现css。
document.body.appendChild(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints rgb(somevalue)
var div2 = document.createElement("div");
div2.style.color = "red";
console.log( $(div2).css("color") ); //prints red because jQuery gives preference to div2.style.color over window.getComputedStyle(div2);
but console.log ( window.getComputedStyle(div2).color );//prints ""   .... this proves that browser has not yet decided the properties of div2