赞
踩
上一节有BOM的讲解,有需要的码客们可以去看一下
以下是一个结合了上述BOM(Browser Object Model)相关内容的练习题及其源代码示例:
练习题:
编写一个JavaScript脚本,该脚本应该执行以下操作:
Screen
对象显示用户的屏幕分辨率。Location
对象跳转到另一个页面。setTimeout
和setInterval
)在控制台打印信息,并展示如何终止setInterval
。源代码示例:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>BOM 编程练习题</title>
- <script>
- window.onload = function() {
- // 1. 显示当前浏览器窗口的宽度和高度
- console.log('外部窗体宽度:', window.outerWidth, '外部窗体高度:', window.outerHeight);
-
- // 2. 显示当前文档显示区域的宽度和高度
- console.log('文档显示区域宽度:', window.innerWidth, '文档显示区域高度:', window.innerHeight);
-
- // 3. 显示用户的屏幕分辨率
- console.log('屏幕分辨率:', screen.width, 'x', screen.height);
-
- // 4. 创建一个新的浏览器窗口并加载URL
- var newWindow = window.open('https://www.example.com', '_blank');
-
- // 5. 刷新当前页面
- function refreshPage() {
- location.reload();
- }
- // 可以调用 refreshPage() 来刷新页面,但这里不直接调用
-
- // 6. 跳转到另一个页面
- function navigateToPage() {
- location.href = 'https://www.anotherexample.com';
- }
- // 可以调用 navigateToPage() 来跳转页面,但这里不直接调用
-
- // 7. 与用户进行交互
- function showAlert() {
- alert('这是一个警告框!');
- }
- function showConfirm() {
- if (confirm('你确定要继续吗?')) {
- alert('你点击了确定!');
- } else {
- alert('你点击了取消!');
- }
- }
- function showPrompt() {
- var inputValue = prompt('请输入你的名字:', '');
- if (inputValue !== null) {
- alert('你好,' + inputValue + '!');
- }
- }
- // 可以调用这些函数来显示不同的对话框
-
- // 8. 使用计时器
- // setTimeout 只执行一次
- setTimeout(function() {
- console.log('setTimeout 执行的消息');
- }, 2000);
-
- // setInterval 不停地重复执行
- var intervalId = setInterval(function() {
- console.log('setInterval 执行的消息');
- // 假设在某个条件下我们要停止定时器
- if (Date.now() > someFutureTime) { // someFutureTime 是某个未来的时间戳
- clearInterval(intervalId);
- }
- }, 1000);
-
- // 注意:不要在setInterval的回调函数中使用document.write(),因为它会重写整个页面
- };
- </script>
- </head>
- <body>
-
- <button onclick="showAlert()">显示警告框</button>
- <button onclick="showConfirm()">显示确认框</button>
- <button onclick="showPrompt()">显示输入框</button>
- <!-- 可以添加更多按钮来调用其他函数 -->
-
- </body>
- </html>

注意:
someFutureTime
在上面的 setInterval
示例中是一个假设的变量,你需要用实际的时间戳替换它。window.open
方法的行为。refreshPage
和navigateToPage
函数在上面的代码中没有被直接调用,但你可以根据需要调用它们。今天就到这里了各位大佬们。
respect!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。