1

在我的新项目中,我必须在没有 jQuery 的情况下做一些内容。我有这个 jQuery 代码:

$(document).ready(function() {
  maxHeight = $("#container").height();
  lastSize = 9;
  while($("#content").height()<maxHeight && lastSize < 1000)
  {
      lastSize++;
    $("#content").css("font-size", lastSize);
  }
  lastSize--;
  $("#content").css("font-size", lastSize);
});

我正在尝试使用本教程用纯 JavaScript 重写它,但它没有正常工作:/ 这是我到目前为止得到的:

document.addEventListener('DOMContentLoaded', function() {
  maxHeight = document.getElementById('container').clientHeight;
  lastSize = 9;
  while(document.getElementById('content').clientHeight<maxHeight && lastSize < 1000)
  {
      lastSize++;
    document.getElementById('content').style.fontSize=lastSize;
  }
  lastSize--;
  document.getElementById('content').style.fontSize=lastSize;
});

我的代码有什么问题?

4

2 回答 2

3

让我按用法查看用法:

1)$(document).ready(f) {}

用这篇文章中的说明替换它

2) 通过 ID 获取元素

maxHeight = $("#container").height();

您可以替换为:

document.getElementById('container').height;

如果height不是你想要调查clientHeightoffsetHeight,等等。

3) 仅使用 JS 更改 CSS 样式

document.getElementById("content").style.fontSize="100";

而不是你的

$("#content").css("font-size", lastSize);

希望这会有所帮助,从小处着手,先尝试 2) 和 3),然后再尝试 1),如果您成功了其他方法。

于 2013-09-11T19:31:56.690 回答
3

解决了

请不要忘记 jquery 关心跨浏览器的兼容性。

http://jsbin.com/opuzur/51/edit

document.addEventListener('readystatechange', function(){
  if(document.readyState != "complete") return;
  container = document.getElementById('container');
  content = document.getElementById('content');
  maxHeight = container.offsetHeight;
  lastSize = 9;
  while(content.offsetHeight < maxHeight){
    content.style['font-size'] = lastSize + 'px';
    lastSize++;
  }
});
于 2013-09-11T19:49:31.590 回答