JS window对象

一、window对象
1.所有浏览器都支持window对象,它表示浏览器窗口
2.所有JS全局对象、函数以及变量均自动成为window对象的成员;
3.全局变量为其属性

var index=0;
console.log(window.index);

4.全局函数为其方法

var index = 0;
window.showName();
function showName() {
     console.log(window.index);
}

5.HTML DOM的document也是window对象的属性之一:window.document.getElementById(“header”);
与document.getElementById(“header”);相同

二、window尺寸
写法一:

console.log(window.screen.width);  //1600  浏览器总宽
console.log(window.screen.availWidth);  //1600  浏览器实际宽
console.log(window.screen.height);  //900  浏览器总高
console.log(window.screen.availHeight);  //860  浏览器实际高

写法二:

document.documentElement.clientWidth;  //获取浏览器可视区域的宽,调试器不算
document.documentElement.clientHeight;  //获取可视区域的高,调试器不算

写法三(不建议使用body,需要清margin,不清则需要计算):

console.log(document.body.clientWidth);  //body的实际宽,比浏览器可视区域的宽少16px,因为浏览器默认外间距margin为8px
console.log(document.body.clientHeight);  //0,body里内容目前为0,body的实际高

写法四:

console.log(window.innerWidth);  //浏览器窗口的内部宽度
console.log(window.innerHeight);  //浏览器窗口的内部高度

三、其他window方法
1.window.open();
打开新窗口
:window.open(url,name,feature,replace);
若name使用名字已经存在,则不会创建一个新窗口,而是会返回对已经存在的窗口的引用;否则,创建一个新窗口

2.window.close();
关闭当前窗口

var btn = document.getElementById("btn");
btn.onclick = function () {
      window.close();
}

3.window.moveTo();
移动当前窗口 被限制

4.window.resizeTo();
语法格式:window.resizeTo(width,height);
width:必需,想要调整到的窗口的宽度,以像素计;
height:可选,想要调整到的窗口的高度,以像素计

window.resizeTo(200,200);  //不能直接使用,必须调整打开的窗口大小
var win = window.open("txt.html", "", "width=100,height=100");
win.resizeTo(300, 300);

四、方法
alert(); //提示框
confirm(“请输入”); //带确认,取消按钮的提示框
prompt(“请输入”,“2”); //带输入文本的提示框

五、window对象里的计时器
1.setTimeout():延迟一段时间,执行一次

var count = 1;
setTimeout(function () {
     count++;
     console.log(count);
}, 1000);  //延迟1s,执行里面的函数一次

例:用setTimeout()实现循环计时器:用函数的递归

var count = 0;
var time;
showtime();
function showtime() {
    count++;
    console.log(count);
    time = setTimeout("showtime()", 1000);
}
//停止加开启计时器
var btnstop = document.getElementById("btnstop");
var btnstart = document.getElementById("btnstart");
btnstop.onclick = function () {
    clearTimeout(time);
}
btnstart.onclick = function () {
    time = setTimeout("showtime()", 1000);
}

2.setInterval():延迟一段时间,循环执行

var time;
var count = 0;
showtime();
function showtime() {
time = setInterval(function () {
    count++;
    console.log(count);
 }, 1000);
}
var btnstop = document.getElementById("btnstop");
var btnstart = document.getElementById("btnstart");
btnstop.onclick = function () {
    clearInterval(time);
};
btnstart.onclick = function () {
    showtime();
}
  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值