我有一段这样的代码:
document.querySelector('.wrap').style.height= lato;
document.querySelector('.wrap').style.width= lato;将两个对象组合在一起的语法是什么?
发布于 2015-01-09 11:10:11
还不完全清楚你在问什么。什么两个物体?如果您正在讨论不必遍历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!发布于 2015-01-09 11:14:58
实际上(仍然是)有一种语法为这个目的设计了,或者不需要键入两次选择器或将其保存到变量中,但是人们不使用它,因为它还有很多其他问题:
with(document.querySelector('.wrap')){ // don't actually do this :D
style.height = lato;
style.width = lato;
// ... all other changes
}尽管如此,惯用的DOM操作会简单地将其缓存到一个变量中,并调用它两次,表示这里的显式性很好,这是非常令人皱眉的。
发布于 2015-01-09 11:10:02
您可以使用cssText:
document.querySelector('.wrap')
.cssText = "height: "+lato+"; width: " + lato + ";";https://stackoverflow.com/questions/27859161
复制相似问题