通过javascript设置css变量

时间:2017-07-17 13:58:50

标签: javascript css-variables

我正在尝试获取浏览器窗口的高度和宽度,并将其显示在正文上以及更改高度以匹配。

这是我目前的代码:

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
}

我知道代码不正确,但我找不到任何可供比较的样本,这里只是代码不够的小提琴。

https://jsfiddle.net/rbtwsxd8/6/

2 个答案:

答案 0 :(得分:1)

这里有许多不同的问题:

  • (至少在小提琴中)你试图在它存在之前document.queryselect标题元素
  • 您的调试代码通过设置document.body
  • 覆盖了header元素
  • 在设置高度和宽度时省略了单位(这用于在“怪癖模式”下工作,但在现代文档类型中不起作用。)
  • 您在尝试设置高度和宽度时添加了额外的双连字符

这是一个纠正这些问题的工作版本:

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;
}

https://jsfiddle.net/pm7rgx4q/1/

答案 1 :(得分:0)

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';
}

fiddle

相关问题