执行此操作的常用方法是将新元素附加到正文,然后像在此jQuery脚本中一样获取计算的css值:
var $body = $('body');
var $this = $(this);
var $text = $this.text();
if($text=='') $text = $this.val();
var calc = '<div style="clear:both;display:block;visibility:hidden;"><span style="width:inherit;margin:0;font-family:' + $this.css('font-family') + ';font-size:' + $this.css('font-size') + ';font-weight:' + $this.css('font-weight') + '">' + $text + '</span></div>';
$body.append(calc);
var width = $body.find('span:last').width();
$body.find('span:last').parent().remove();
return width;
问题是如何在不将其附加到DOM的情况下执行此操作以避免缓慢重新渲染,此脚本在不将其附加到DOM的情况下执行此操作:
var fakeInputText = '<div style="clear:both;display:block;"><span style="width:inherit;margin:0;font-family:Helvetica Neue, Helvetica, Arial, sans-serif;font-size:22px;font-weight:400"></span></div>';
var parser = new DOMParser();
var doc = parser.parseFromString(fakeInputText, "text/html");
var style = document.defaultView.getComputedStyle(doc.getElementsByTagName("div")[0]); //doc.querySelector("span")
console.log(style);
这就是它得到的:
答案 0 :(得分:0)
您可以创建一个jQuery元素,而无需将其附加到DOM。
var $yourCachedElement = $("<div>", { // Create your element
style: "your styling",
html: "html code to store inside this element"
}),
widthYouWannGet = $yourCachedElement.width(); // Store element's width into the var