前端JS-21

目录

Location

对象属性

对象方法

对象描述

 完整代码

 Screen

对象属性

对象描述

定时器简介

基本用法

 setInterval 和 setTimeout的区别

面试题

延时调用

例子

轮播图界面

html

css 

javascript 

点击按钮切换图片

搭建基本的结构

设置显示的样式

javascript部分


Location

对象属性

属性描述
hash设置或返回从井号 (#) 开始的 URL(锚)。
host设置或返回主机名和当前 URL 的端口号。
hostname设置或返回当前 URL 的主机名。
href设置或返回完整的 URL。
pathname设置或返回当前 URL 的路径部分。
port设置或返回当前 URL 的端口号。
protocol设置或返回当前 URL 的协议。
search

设置或返回从问号 (?) 开始的 URL(查询部分)。

对象方法

属性描述
assign()加载新的文档。
reload()重新加载当前文档。
replace()用新的文档替换当前文档。

对象描述

Location 对象存储在 Window 对象的 Location 属性中,表示那个窗口中当前显示的文档的 Web 地址。它的 href 属性存放的是文档的完整 URL,其他属性则分别描述了 URL 的各个部分。这些属性与 Anchor 对象(或 Area 对象)的 URL 属性非常相似。当一个 Location 对象被转换成字符串,href 属性的值被返回。这意味着你可以使用表达式 location 来替代 location.href。

不过 Anchor 对象表示的是文档中的超链接,Location 对象表示的却是浏览器当前显示的文档的 URL(或位置)。但是 Location 对象所能做的远远不止这些,它还能控制浏览器显示的文档的位置。如果把一个含有 URL 的字符串赋予 Location 对象或它的 href 属性,浏览器就会把新的 URL 所指的文档装载进来,并显示出来。

除了设置 location 或 location.href 用完整的 URL 替换当前的 URL 之外,还可以修改部分 URL,只需要给 Location 对象的其他属性赋值即可。这样做就会创建新的 URL,其中的一部分与原来的 URL 不同,浏览器会将它装载并显示出来。例如,假设设置了Location对象的 hash 属性,那么浏览器就会转移到当前文档中的一个指定的位置。同样,如果设置了 search 属性,那么浏览器就会重新装载附加了新的查询字符串的 URL。

除了 URL 属性外,Location 对象的 reload() 方法可以重新装载当前文档,replace() 可以装载一个新文档而无须为它创建一个新的历史记录,也就是说,在浏览器的历史列表中,新文档将替换当前文档。

 完整代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			/*
			 Location
			 -该对象中封装了浏览器的地址栏信息
			 */
			window.onload=function(){
				
				//获取按钮对象
				var btn=document.getElementById("btn");
				btn.onclick=function(){
					
					//如果直接打印location,则可以获取到地址栏信息(当前页面的完整路径)
					//alert(location);
					/*
					 * 如果直接将location属性修改为一个完整的路径,或相对路径
					 * 则我们页面会自动跳转到该路径,并且会生成相应的历史记录
					 */
					
					//location="http://www.baidu.com";
					//location="01.BOM.html";
					//location="http://www.baidu.com";
					
					/*
					 * assign()
					 * -用来跳转到其他的页面,作用和直接修改location一样
					 */
					
					//location.assign("http://www.baidu.com");
					
					/*
					 * reload
					 * -用于重新加载当前页面,作用和刷新按钮一样
					 * -如果在方法中传递一个true,作为参数,则会强制清空缓存刷新页面
					 */
					//location.reload(true);
					
					/*
					 * replace()
					 * -可以使用一个新的页面替换当前页面,调用完毕也会跳转页面
					 * 不会生成历史记录,不能使用回退按钮回退
					 */
				};
			};
		</script>
	</head>
	<body>
	</body>
</html>

 Screen

Screen 对象包含有关客户端显示屏幕的信息。

注释:没有应用于 screen 对象的公开标准,不过所有浏览器都支持该对象。

对象属性

属性描述
availHeight返回显示屏幕的高度 (除 Windows 任务栏之外)。
availWidth返回显示屏幕的宽度 (除 Windows 任务栏之外)。
bufferDepth设置或返回调色板的比特深度。
colorDepth返回目标设备或缓冲器上的调色板的比特深度。
deviceXDPI返回显示屏幕的每英寸水平点数。
deviceYDPI返回显示屏幕的每英寸垂直点数。
fontSmoothingEnabled返回用户是否在显示控制面板中启用了字体平滑。
height返回显示屏幕的高度。
logicalXDPI返回显示屏幕每英寸的水平方向的常规点数。
logicalYDPI返回显示屏幕每英寸的垂直方向的常规点数。
pixelDepth返回显示屏幕的颜色分辨率(比特每像素)。
updateInterval设置或返回屏幕的刷新率。
width返回显示器屏幕的宽度。

对象描述

每个 Window 对象的 screen 属性都引用一个 Screen 对象。Screen 对象中存放着有关显示浏览器屏幕的信息。JavaScript 程序将利用这些信息来优化它们的输出,以达到用户的显示要求。例如,一个程序可以根据显示器的尺寸选择使用大图像还是使用小图像,它还可以根据显示器的颜色深度选择使用 16 位色还是使用 8 位色的图形。另外,JavaScript 程序还能根据有关屏幕尺寸的信息将新的浏览器窗口定位在屏幕中间。

定时器简介

  • timeoutId: 定时器ID
  • func: 延迟后执行的函数
  • code: 延迟后执行的代码字符串,不推荐使用原理类似eval()
  • delay: 延迟的时间(单位:毫秒),默认值为0
  • param1,param2: 向延迟函数传递而外的参数,IE9以上支持
  • setInterval: 以固定的时间间隔重复调用一个函数或者代码段
  • setImmediate: 在浏览器完全结束当前运行的操作之后立即执行指定的函数
  • requestAnimationFrame: 专门为实现高性能的帧动画而设计的API,但是不能指定延迟时间,而是根据浏览器的刷新频率而定(帧)

基本用法

var intervalId, timeoutId;

timeoutId = setTimeout(function () {
    console.log(1);
}, 300);

setTimeout(function () {
    clearTimeout(timeoutId);
    console.log(2);
}, 100);

setTimeout('console.log("5")', 400);

intervalId = setInterval(function () {
    console.log(4);
    clearInterval(intervalId);
}, 200);

 setInterval 和 setTimeout的区别

// 执行在面的代码块会输出什么?
setTimeout(function () {
    console.log('timeout');
}, 1000);

setInterval(function () {
    console.log('interval')
}, 1000);

// 输出一次 timeout,每隔1S输出一次 interval

/*--------------------------------*/

// 通过setTimeout模拟setInterval 和 setInterval有啥区别么?
var callback = function () {
    if (times++ > max) {
        clearTimeout(timeoutId);
        clearInterval(intervalId);
    }

    console.log('start', Date.now() - start);
    for (var i = 0; i < 990000000; i++) {}
    console.log('end', Date.now() - start);
},
delay = 100,
times = 0,
max = 5,
start = Date.now(),
intervalId, timeoutId;

function imitateInterval(fn, delay) {
    timeoutId = setTimeout(function () {
        fn();

        if (times <= max) {
            imitateInterval(fn ,delay);
        }
    }, delay);
}

imitateInterval(callback, delay);
intervalId = setInterval(callback, delay);

面试题

// 题目一
var t = true;
 
setTimeout(function(){
    t = false;
}, 1000);
 
while(t){}
 
alert('end');

/*--------------------------------*/

// 题目二
for (var i = 0; i < 5; i++) {
    setTimeout(function () {
        console.log(i);
    }, 0);
}

/*--------------------------------*/

// 题目三
var obj = {
    msg: 'obj',
    shout: function () {
        alert(this.msg);
    },
    waitAndShout: function() {
        setTimeout(function () {
            this.shout();
        }, 0);    
    }
};
obj.waitAndShout();

延时调用

在js中,延迟执行函数有两种:
setTimeout和setInterval

setTimeout("test()","2000");  //2000毫秒后执行test()函数,只执行一次。
setInterval("test()","2000"); //每隔2000毫秒执行一次test()函数,执行无数次。
var interval = window.setInterval("test()","2000");
window.clearInterval(interval);     //停止执行setInterval循环。

当我们想让test()函数每隔2000毫秒执行一次,执行10000毫秒后停止执行时,可以用两者三者结合使用来实现。
var interval2 = window.setInterval("openit2()",2000);
setTimeout(function() {window.clearInterval(interval2);},10000);

带参方法执行延迟
setTimeout(function(){return executeQueryTask(data);},"10000");

例子

<html>
  <head>    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <script>
        var num = 3;
        window.onload = function(){
            var s = window.setInterval(function(){
                document.getElementById("s").innerHTML=num;
                num--;
                if(num<=0){
                    window.close();

                }
            }, 1000);            
        }
    </script>
    
  </head>
  <body>
        <h1><s:property value="msg"/></h1>
        <h2>本窗口在<span id="s">3</span>秒之后关闭!</h2>
        <input type=button value=关闭窗口  onclick="window.close();"  />
  </body>
</html>

轮播图界面

html

<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <link rel="stylesheet" href="carousel.css" rel="external nofollow" >
 <title>轮播图效果</title>
</head>
<body>
 <section id="main">
 <div id="picture"></div>
 <!-- 添加图中按钮 图片轮播在js中大致成型后再写最好-->
 <div id="dot">
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 </div>
 
 <!-- 添加切换按钮 -->
 <div id="an">
  <div class="left">&lt;</div>
  <div class="right">&gt;</div>
 </div>
 </section>
 <script src="jquery.js"></script>
 <script src="carousel.js"></script>
</body>

css 

#main{
 width: 655px;
 height: 361px;
 position: relative;
}
#picture{
 width:100%;
 height: 100%;
}
#picture img{
  
 width:100%;
 height: 100%;
 display: none;
}
 
#picture img:nth-child(1){
 display: inline-block;
}
 
 
/* 设置圆点的样式 */
#dot span{
 display: inline-block;
 width:25px;
 height: 25px;
 border-radius: 50%;
 background-color: gray;
 margin-left: 10px;
 opacity: 0.6
}
 
 
#dot{
 position: absolute;
 right: 40px;
 bottom: 30px;
}
 
 
/* 设置页面刚加载的圆点初始状态 1 第一个圆点放大1.2倍 2、颜色变成蓝色
 */
 #dot :nth-of-type(1){
 transform: scale(1.2);
 background-color: blue;
 }
 
 
 .left ,.right{
  
 width: 40px;
 height: 40px;
 border-radius: 50%;
 font-size: 30px;
 color: white;
 position: absolute;
 bottom: calc((100% - 40px)/2);
 text-align: center;
 }
 
 
 .left{
 left: 15px;
 }
 .right{
 right: 15px;
 }
 
 
 .left:hover ,.right:hover{
 background-color: white;
 color:red;
 }

javascript 

for(var i=1; i<6;i++){
 $('#picture').append("<img src='./../images/"+i+".jpg' >");
}
//给图片转化设置定时函数
var index=0;
var timer;
function changeImageDot(){
 $('#picture img:nth-child('+(index+1)+')').css({
 display:'block',
 }).siblings().css({
 display:'none',
 });
 //设置随图片切换,对应的圆点样式发生变化
 // index+1 是因为索引是从0开始而 nth-child(i) 中的i是从1 开始的
 $('#dot span:nth-child('+(index+1)+')').css({
 transform: 'scale(1.2)',
 'background-color': 'blue',
 }).siblings().css({
 transform: 'scale(1)',
 'background-color':'gray',
 });
}
function produceTime(){
 timer=setInterval(function(){
 index++;
 if(index==5) 
 index=0;
 changeImageDot();
  
 },2000);
}
 
produceTime();
//鼠标悬浮在圆点上 , 圆点和图片的变化
$('#dot span').mouseenter(function(){
 index=$(this).index();
 changeImageDot(); 
 clearInterval(timer); 
 produceTime(); 
});
//缺点:点击切换按钮后,图片切换后 ,会立即切换到下一个图片,需要设置 清除计时器后再新建一个计时器
$('.left').click(function(){
 index--;
 if(index==-1)
 index=4;
 changeImageDot(); 
 clearInterval(timer);
 produceTime();
 
 
});
 
 
$('.right').click(function(){
 index++;
 if(index==5)
 index=0;
 changeImageDot();
 clearInterval(timer);
 produceTime();

点击按钮切换图片

搭建基本的结构

<div id="div">
        <p id="desc"></p>
        <!--默认显示第一张图片-->
        <img src="img/1.jpg" alt="加载失败" style="width: 800px;height: 400px;">
        <button id="pre">上一张</button>
        <button id="next">下一张</button>
</div>

设置显示的样式

<style>
        * {
            margin: 0;
            padding: 0;
        }
     
        #div {
            width: 800px;
            height: 420px;
            margin: 20px auto;
            background-color: rgb(243, 119, 36);
            text-align: center;
        }
     
        button:hover {
            cursor: pointer;
        }
</style>

javascript部分

<script>
        //预加载,等页面加载完毕后,再执行脚本
        window.onload = function () {
          
            var num = document.getElementsByTagName("img")[0];
            //这里虽然只有一个img标签,但是num变量的结果依然是一个数组
             
            //定义图像地址
            var shuzu = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg", "img/6.jpg", "img/7.jpg", "img/8.jpg", "img/9.jpg", "img/10.jpg", "img/11.jpg", "img/12.jpg"];
 
            //获取按钮
            var prev = document.getElementById("pre");
            var next = document.getElementById("next");
            var index = 0;
             
            //图片描述
            var p_desc = document.getElementById("desc");
            p_desc.innerHTML = "一共" + shuzu.length + "张图片" + ",当前是第" + (index + 1) + "张";
            //注意此处前面是字符串的拼接,实现加法需要用到括号
             
            //点击切换图片
            prev.onclick = function () {
                index--;
                //此处让它循环
                if (index < 0)
                    index = shuzu.length - 1;
                num.src = shuzu[index];
                p_desc.innerHTML = "一共" + shuzu.length + "张图片" + ",当前是第" + (index + 1) + "张";//注意此处前面是字符串的拼接,实现加法需要用到括号
            }
 
            next.onclick = function () {
                index++;
                if (index > shuzu.length - 1)
                    index = 0;
                num.src = shuzu[index];
                p_desc.innerHTML = "一共" + shuzu.length + "张图片" + ",当前是第" + (index + 1) + "张";//注意此处前面是字符串的拼接,实现加法需要用到括号
            }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值