为什么这个JavaScript函数在Firefox上这么慢? [英] Why is this javascript function so slow on Firefox?

查看:144
本文介绍了为什么这个JavaScript函数在Firefox上这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个功能改编自网站: http://eriwen.com/javascript / measure-ems-for-layout /

$ $ $ $ $ $ $ $ $ var tempDiv =使用document.createElement( DIV);
tempDiv.style.height =1em;
el.appendChild(tempDiv);
var emSize = tempDiv.offsetHeight;
el.removeChild(tempDiv);
返回emSize;





我将这个函数作为window.resize的另一个函数的一部分运行,它在Firefox 3.6上导致性能问题,在当前的Safari或Chrome上不存在。 Firefox的配置文件说,我花了大部分时间在这个功能,我很好奇,为什么。



有没有一种方法可以在JavaScript中获得em大小,而不用做所有这些工作?我想重新调整resize的大小incase用户已经改变它。

解决方案

似乎函数可能只是

($)
$ b $ pre $ function getEmSize(el){
return Number(getComputedStyle(el,).fontSize.match(/ \\d +)PX /)[1]);





$ b换句话说,你可以得到元素的计算字体大小比创建一个div和大小。


This function was adapted from the website: http://eriwen.com/javascript/measure-ems-for-layout/

function getEmSize(el) {
    var tempDiv = document.createElement("div");
    tempDiv.style.height = "1em";
    el.appendChild(tempDiv);
    var emSize = tempDiv.offsetHeight;
    el.removeChild(tempDiv);
    return emSize;
}

I am running this function as part of another function on window.resize, and it is causing performance problems on Firefox 3.6 that do not exist on current Safari or Chrome. Firefox's profiler says I'm spending the most time in this function and I'm curious as to why that is.

Is there a way to get the em size in javascript without doing all this work? I would like to recalculate the size on resize incase the user has changed it.

解决方案

Seems like the function could just be

function getEmSize(el) {
    return Number(getComputedStyle(el, "").fontSize.match(/(\d+)px/)[1]);
}

In other words, you can just get the computed font size of the element rather than creating a div and sizing it.

这篇关于为什么这个JavaScript函数在Firefox上这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆