我有一段这样的代码:
document.querySelector('.wrap').style.height= lato;
document.querySelector('.wrap').style.width= lato;
将两个对象组合在一起的语法是什么?
答案 0 :(得分:1)
你所要求的并不完全清楚。两个对象是什么?如果你在谈论不必遍历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!
答案 1 :(得分:1)
实际上 (仍然是)语法设计用于此目的,或者不必将选择器键入两次或将其保存到变量中但人们不会#39 ;使用它,因为它有很多其他问题:
with(document.querySelector('.wrap')){ // don't actually do this :D
style.height = lato;
style.width = lato;
// ... all other changes
}
但是,非常不赞成,惯用的DOM操作只会将其缓存到一个变量中并调用它两次,说这里的显式性很好。
答案 2 :(得分:0)
您可以使用cssText:
document.querySelector('.wrap')
.cssText = "height: "+lato+"; width: " + lato + ";";