使用窗口对象练习我的对象文字函数

Practicing my object literal functions using the window object

本文关键字:对象 文字 函数 我的 练习 窗口      更新时间:2023-09-26

我是使用JavaScript函数的新手,我使用窗口对象创建了一个对象文字函数。我不确定做这样的函数是否正确?我会发布代码,并链接到我的代码笔,这样你就可以看到功能的作用。现在,要查看各种窗口和屏幕高度是多少,您必须调整浏览器宽度和刷新页面,宽度和高度也应相应调整。提前感谢你能给我的任何帮助。

代码笔整页视图:http://codepen.io/mike316/full/eZKYRE/

<!doctype html>
    <html>
      <head>
         <meta charset="utf-8">
         <title>Template</title>
         <link rel="stylesheet" href="css/styles.css">
      </head>
      <body>
        <div class="wrapper">
          <h1>JavaScript Fun</h1>
          <span id="fun"></span>
          <script src="js/scripts.js"></script>
        </div>
     </body>
   </html>

使用html、CSS和JavaScript编写代码笔。http://codepen.io/mike316/pen/eZKYRE

我的CSS:

body {
   background: grey;
}
.wrapper {
    background: teal;
    border: 2px solid black;
    border-radius: 15px;
    max-width: 60em;
    margin: 0 auto;
}
h1,
h2,
 p {
    text-align: center;
 }

下面的我的JavaScript:

var info = {
     windowHeight: "<h2>Browser Window</h2><p>width:" + window.innerWidth + "</p>",
     windowWidth: "<p>height: " + window.innerHeight + "</p>,
     screenWidth: "<h2>screen</h2><p>Width:" + window.screen.width + "</p>",
     screenHeight: "<p>height: " + window.screen.height + "</p>
     screenInfo: function() {
         return this.windowHeight + this.windowWidth + this.screenWidth + this.screenHeight;
     }
};

调用我的函数

document.getElementById("fun").innerHTML = info.screenInfo();

这很好,但我建议进行调整。不要在这里使用对象。它不会在语义上添加任何内容,并且html属性在页面加载时被锁定,除非您再次创建该对象。你最好只使用函数和变量!

以下代码段与您的代码执行相同的操作,只是每当您调整屏幕宽度时都会运行该函数,这样您就不必刷新页面来查看新值代码笔

function screenInfo () {
  var windowHeight = "<h2>Browser Window</h2><p>width:" + window.innerWidth + "</p>"
  var windowWidth = "<p>height: " + window.innerHeight + "</p>"
  var screenWidth = "<h2>screen</h2><p>Width:" + window.screen.width + "</p>"
  var screenHeight = "<p>height: " + window.screen.height + "</p>"
  return windowHeight + windowWidth + screenWidth + screenHeight;
}
function addHtml () {
  document.getElementById("fun").innerHTML = screenInfo()
}
window.onresize = addHtml
addHtml()