通过javascript设置一个css变量
我想获取浏览器窗口的高度和宽度,并将其显示在主体上以及更改高度以匹配。通过javascript设置一个css变量
这里是我当前的代码:
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
上面的代码显示在机身的宽度和高度确定,现在是时候将它添加到CSS的变量:
var header = document.querySelector('.header')
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
header.style.setProperty('--height', height);
header.style.setProperty('--width', width);
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
我知道代码是不正确的,但我找不到任何样本进行比较,这里是一个小提琴,以防代码不足。
你有许多不同的问题在这里:
- (至少在小提琴)你试图
document.queryselect
头元素之前存在的 - 您的调试代码通过设置012覆盖标题元素
- 您设置的高度和宽度(这适用于“兼容模式”来工作,但不会在现代的doctype工作。)
- 你想设置的高度和宽度 当添加额外的双连字符时省略单位
下面是其纠正这些问题的工作版本:
window.onresize = window.onload = function() {
var header = document.querySelector('.header');
// your original code used 'this.innerWidth' etc, which does work
// (because the function is being run on the window object) but can
// be confusing; may be better to refer to the window object
// explicitly:
var width = window.innerWidth;
var height = window.innerHeight;
header.style.width = width + "px"; // need 'px' units
header.style.height = height + "px";
// the above is equivalent shorthand for
// header.style.setProperty('height', window.innerHeight + 'px');
// header.style.setProperty('width', window.innerWidth + 'px');
// setting this inside the header, so we don't remove it in the process:
header.innerHTML = width + "x" + height;
}
但是,这里的CSS变量在哪里? “风格”下的 –
。 'foo.style'是DOM元素'foo'的CSS对象。 –
代码中没有任何CSS变量... –
window.onresize = window.onload = function() {
var header = document.querySelector('.header')
width = this.innerWidth;
height = this.innerHeight;
header.innerHTML = width + 'x' + height; // For demo purposes
header.style.setProperty('height', height + 'px')
header.style.setProperty('width', width + 'px');
//header.style.height = height + 'px';
//header.style.width =width + 'px';
}
在这种情况下,我并不是downvoter,但这是我经常做的* do * downvote的答案:它只是一个代码转储,没有解释原始代码的错误。 –
提问者只是要求比较的代码。让他通过询问来学习。 –
我不同意这很有帮助,@FazalRasel,但这就是为什么有一个upvote/downvote系统首先:我们都得到投票,什么构成一个好的答案。 –
你在控制台看......? 'header'是'null'。您已将代码放入'
'中,无需等待文档加载,因此选择器将无法找到它们的元素。您也正在重新调整''的大小,从而完全删除您的“标题”元素。 – Santi抱歉,我是javascript新手。不明白为什么这是null,如果我使用document.getElementById(“header”)并将该类更改为div上的id并替换该行,则header.style.setProperty(' - height',height);与document.getElementById(“header”)。style.setProperty(' - height',height);我认为虽然我的尺寸仍然没有变化 – Dan
在JSFiddle中,您已将代码设置为嵌入*“不包装在
”*中,这意味着它将嵌入在您的页面头部的'