举例说明常用的BOM属性和方法有哪些?

好的,以下是一些常用的 BOM 属性和方法的示例,并附带说明:

Window 对象属性:

  • innerWidth / innerHeight: 获取浏览器窗口内部的宽度和高度(不包括菜单栏、工具栏等)。

    console.log("Inner Width:", window.innerWidth);
    console.log("Inner Height:", window.innerHeight);
    
  • outerWidth / outerHeight: 获取浏览器窗口外部的宽度和高度(包括菜单栏、工具栏等)。

    console.log("Outer Width:", window.outerWidth);
    console.log("Outer Height:", window.outerHeight);
    
  • screen.width / screen.height: 获取用户屏幕的宽度和高度。

    console.log("Screen Width:", screen.width);
    console.log("Screen Height:", screen.height);
    
  • location: 包含当前 URL 的信息。 一些常用的属性包括:

    • href: 获取或设置完整的 URL。
    • pathname: 返回 URL 的路径部分。
    • hostname: 返回 URL 的主机名。
    • protocol: 返回 URL 的协议。
    console.log("Current URL:", window.location.href);
    console.log("Pathname:", window.location.pathname);
    window.location.href = "https://www.example.com"; // 跳转到新页面
    
  • navigator: 包含浏览器的信息。

    • userAgent: 返回用户代理字符串,可以用来识别浏览器类型和版本。
    • platform: 返回运行浏览器的操作系统平台。
    console.log("User Agent:", window.navigator.userAgent);
    console.log("Platform:", window.navigator.platform);
    

Window 对象方法:

  • alert(): 显示一个警告框。

    alert("Hello, world!");
    
  • confirm(): 显示一个确认框,返回 truefalse

    let confirmed = confirm("Are you sure?");
    if (confirmed) {
      // 用户点击了“确定”
    } else {
      // 用户点击了“取消”
    }
    
  • prompt(): 显示一个输入框,返回用户输入的值或 null

    let name = prompt("Please enter your name:", "Guest");
    if (name != null) {
      console.log("Hello, " + name + "!");
    }
    
  • open(): 打开一个新的浏览器窗口或标签页。

    window.open("https://www.google.com", "_blank");
    
  • close(): 关闭当前窗口或标签页。

    window.close(); // 通常只允许关闭通过 JavaScript 打开的窗口
    
  • setTimeout(): 设置一个定时器,在指定时间后执行一次代码。

    setTimeout(() => {
      console.log("This will run after 2 seconds");
    }, 2000); // 2000 毫秒 = 2 秒
    
  • setInterval(): 设置一个定时器,每隔指定时间重复执行代码。

    let intervalId = setInterval(() => {
      console.log("This will run every second");
    }, 1000);
    
    // 停止定时器
    clearInterval(intervalId);
    
  • scrollTo(): 滚动窗口到指定位置。

    window.scrollTo(0, 100); // 滚动到垂直位置 100px
    

这只是一些常用的 BOM 属性和方法,还有很多其他的属性和方法可以用来操作浏览器窗口和文档。 建议查阅 MDN Web Docs (https://developer.mozilla.org/en-US/docs/Web/API/Window) 获取更完整的 BOM 参考。

posted @ 2024-11-29 03:20  王铁柱6  阅读(22)  评论(0)    收藏  举报