gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:58:18 27 4
gpt4 key购买 nike

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

这段代码有效,我正在尝试计算 div 中的行数。也就是说,直到我将此元素添加到 DOM 后,我才能够获取行高。

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

在我添加它之前它不会有高度,这是有道理的,我只是想知道我是否做了正确的事情,或者是否有一种方法可以获取行高而不将其添加到 DOM 中第一名。

最佳答案

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

1)插入新元素

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

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

因此,直到元素位于 DOM Tree 中之前,浏览器不会为其提供与布局相关的样式。

考虑以下代码:

var div = document.createElement(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints "" (empty string)
为什么?因为 window.getComputedStyle() 返回实际存在于 DOM(浏览器)中的 CSS 样式。现在,

document.body.appendChild(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints rgb(somevalue)
为什么?因为渲染引擎已经决定了CSS属性。

//一个陷阱

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

关于javascript - Jquery/Javascript 是否需要 DOM 中的元素才能使用 .css()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20802595/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com