简体   繁体   English

JavaScript window.innerwidth 无法正常工作

[英]JavaScript window.innerwidth doesnt work correct

I'm new to JavaScript and wanted to make a simple "hello world" program with changing text based on the width on the screen.我是 JavaScript 的新手,想制作一个简单的“hello world”程序,根据屏幕上的宽度更改文本。 If the width of the window (of the index file) is 400 or more pixels, show text, and if the window is smaller then 400px show other text.如果窗口(索引文件)的宽度为 400 或更多像素,则显示文本,如果窗口较小,则 400px 显示其他文本。 I do not know why my code does not work.我不知道为什么我的代码不起作用。 Can somebody please explain this to me, thanks in advance有人可以向我解释一下吗,提前致谢

this is my code (HTML and JavaScript )这是我的代码(HTML 和 JavaScript)

HTML = HTML =

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavascriptResponsive</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Hello world </h1>
<script src="Morris.js"></script>
</body>
</html>

JavaScript = JavaScript =

    var currentWidth = window.innerWidth;
if (currentWidth > 400) {
    document.write(" <h1>Hello big world </h1>");

}
else if (currentWidth < 400) {
    document.write( "<h1>Hello small world </h1>");
}

When JavaScript code is run the variables do not keep updating and running.当 JavaScript 代码运行时,变量不会不断更新和运行。 So you need to write code to detect when things change.因此,您需要编写代码来检测事物何时发生变化。 So you need to listen to the resize event.所以你需要监听 resize 事件。 So you bind an event listener and you can rerun the code.所以你绑定了一个事件监听器,你可以重新运行代码。 You also can not use document.write to output the message after the page loads since it will remove all the page content.您也不能使用 document.write 在页面加载后输出消息,因为它会删除所有页面内容。 So you want to update the DOM.所以你想更新DOM。

 function updateMessage() { var currentWidth = window.innerWidth; var message = "Hello small world"; if (currentWidth > 400) { message = "Hello big world"; } document.getElementById("msg").innerHTML = message } window.addEventListener("load", updateMessage) window.addEventListener("resize", updateMessage)
 <h1 id="msg">Hello world </h1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM