Javascript 组合querySelector()方法

Javascript 组合querySelector()方法,javascript,Javascript,我有一段代码如下: document.querySelector('.wrap').style.height= lato; document.querySelector('.wrap').style.width= lato; 将两个对象合并为一个对象的语法是什么?您可以使用cssText: document.querySelector('.wrap') .cssText = "height: "+lato+"; width: " + lato + ";"; 你问的

我有一段代码如下:

    document.querySelector('.wrap').style.height= lato;
    document.querySelector('.wrap').style.width= lato;
将两个对象合并为一个对象的语法是什么?

您可以使用cssText:

document.querySelector('.wrap')
      .cssText = "height: "+lato+"; width: " + lato + ";";

你问的问题并不完全清楚。哪两个物体?如果您谈论的是不必两次遍历DOM来访问同一个元素,我建议在第一次访问元素后缓存该元素:

var wrap = wrap || document.querySelector('.wrap');
wrap
的第一次引用将确保其值被分配给
document.querySelector()
,后续引用将使用缓存版本

wrap.style.height = lato; //Navigates through the DOM to find the element
wrap.style.width = lato; //Element is now cached, no DOM traversing needed!
实际上(现在仍然)有一种语法正是为了这个目的而设计的,或者不必两次键入选择器或将其保存到变量中,但人们不使用它,因为它还有很多其他问题:

with(document.querySelector('.wrap')){ // don't actually do this :D
    style.height = lato;
    style.width = lato; 
    // ... all other changes
}

这是非常不赞成的,惯用的DOM操作只需将其缓存到变量中,并调用两次,说明这里的明确性很好。

document.queryselectoral?所以您认为调用两次是最佳选择?@maioman我认为如果您不想模仿像jQuey这样的库,将其缓存到变量中是最佳选择。性能方面,与样式相比,targeting.cssText有任何缺点。height@maioman您不应该关心这些场景中的性能。使用
.cssText
有一个陷阱,即它将覆盖任何其他已分配的样式,这使得它不值得使用。