JavaScriptwindow(六)

  • window对象(Dom中的一个顶级对象)
  1. window对象代表当前浏览器窗口。
  2. 使用window对象的属性、方法的时候可以省略window。
  3. 比如:
    • window.alert(‘hello');可以省略成alert(‘hello');
    • window.document可以直接写document
  4. 能不写window就不要写,这样可以减少js文件的字节数。
  • window对象的方法
  1. window.alert(‘大家好!’);//弹出警告对话框
  2. window.confirm(‘确定要删除吗?’);//确定、取消对话框,返回true或false;
  3. window.navigate(url);//将网页重新导航到url,只支持IE、Opera11.6,建议使用window.location.href=‘url’;//支持大多数浏览器
  1. window.setInterval(code,delay)//每隔一段时间执行指定的代码(类似于winForm中的Timer控件。)
    • 第一个参数:指定的代码字符串
    • 第二个参数:时间间隔(毫秒数)
    • var intervalId=setInterval(“alert(‘hello’);”,1000);

例:让文本框的数值自增

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></title>

   <meta charset="utf-8" />

    <script type="text/javascript">

        setInterval(function ()

        {

            var num = txt.value;

            num = parseInt(num) + 1;

            txt.value = num;

        }, 1000)

    </script>

</head>

<body>

   <input type="text" id="txt" value="1"/>

</body>

</html>

  1. window.clearInterval(intervalId);//停止计时器
    • clearInterval()取消setInterval的定时执行,相当于Timer中的Enabled=False。因为setInterval可以设定多个定时,所以clearInterval要指定清除那个定时器的标识,即setInterval的返回值。

注:<input type="button" value="滚动" οnclick="setInterval('scroll()', 500)" />

每调用一次setInterval都会产生一个新的定时器,并且旧的不会自动停止。所以看起来好像“越跑越快”!

clearInterval(setInterval('scroll()', 500)),错,不会停止原先的定时器,因为setInterval就产生一个新的定时器,刚产生就被clear

应用举例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

    <title>北京欢迎你</title>

    <script type="text/javascript">

        var timerId;

        function scroll() {

            var title = document.title;

            var lastCh = title.charAt(title.length - 1); //容易错

            var leftStr = title.substring(0, title.length - 1);

            document.title = lastCh + leftStr;

        }

        //每调用一次setInterval都会产生一个新的定时器,并且旧的不会自动停止。所以看起来好像“越跑越快”!

    </script>

</head>

<body>

<input type="button" value="滚动" οnclick="if(timerId){clearInterval(timerId);}timerId=setInterval('scroll()', 500)" />

<input type="button" value="停止(错误写法)" οnclick="clearInterval(setInterval('scroll()', 500))" />

<input type="button" value="停止" οnclick="clearInterval(timerId)" />

</body>

</html>

例:利用定时器实现跑马灯效果.

<html>

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>0123456789</title>

    <meta charset="utf-8" />

    <script type="text/javascript">

        var dir = "left";

        setInterval(function () {

            var title = document.title;

            var first;

            var last;

            if (dir == 'left') {

                first = title.substr(0, 1);

                last = title.substr(1);

            } else {

                first = title.substring(0, title.length - 1);

                last = title.substring(title.length - 1, title.length);

            }

            document.title = last + first;

        }, 1000)

        function setDir(d)

        {

            dir = d;

        }

    </script>

</head>

<body>

    <input id="Button1" type="button" value="向左" οnclick="setDir('left')" />

    <input id="Button2" type="button" value="向右" οnclick="setDir('right')"/>

</body>

</html>

  • bodydocument对象的事件
  1. onload(页面加载后触发)
    • 网页加载完毕时触发,浏览器是一边下载文档、一边解析执行,可能会出现JavaScript执行时需要操作某个元素,这个元素还没有加载,如果这样就要把操作的代码放到body的onload事件中,或者可以把JavaScript放到元素之后。元素的onload事件是元素自己加载完毕时触发,body onload才是全部加载完成。
    • window.控件Id(不建议使用)
    • document.getElementById(“控件Id”);(推荐)
  2. 除了属性之外,当然还有通用的HTML元素的事件:onclick(单击)、ondblclick(双击)、onkeydown(按键按下)、onkeypress(点击按键)、onkeyup(按键释放)、onmousedown(鼠标按下)、onmousemove(鼠标移动)、onmouseout(鼠标离开元素范围)、onmouseover(鼠标移动到元素范围)、onmouseup(鼠标按键释放)、oncontextmenu(在浏览器中单击鼠标右键显示”右键菜单”时触发)等。
  • window对象的属性
  1. window.location对象:
    • window.location.href=‘’;//重新导航到新页面,可以取值,也可以赋值。
    • window.location.reload();//刷新当前页
  2. window.event是IE下非常重要的属性,用来获得发生事件时的信息,事件不局限于window对象的事件,所有元素的事件都可以通过event属性取到相关信息。类似于winForm中的e(EventArgs)。//兼容IE、Chrome,不兼容FF(用event参数)。
    • window.event.altKey属性,bool类型,表示事件发生时是否按下了alt键。类似的还有ctrlKey,shiftKey。演示:<input type="button" value="点击" οnclick="if(event.altKey){alert('Alt点击')}else{alert('普通点击')}" /> ;
  • clientX、clientY 发生事件时鼠标在客户区的坐标;screenX、screenY 发生事件时鼠标在屏幕上的坐标;offsetX、offsetY 发生事件时鼠标相对于事件源(比如点击按钮时触发onclick)的坐标。

<script type="text/javascript">

        document.onmousemove = function ()

        {//鼠标在文档上的位置。

            // document.title = window.event.clientX + "==" + window.event.clientY;

            //鼠标早屏幕上的位置。

            //document.title = window.event.screenX + '==' + window.event.screenY;

            //相对事件源的位置。

            document.title = window.event.offsetX + '==' + window.event.offsetY;

        }

    </script>

  • (window.event.returnValue)returnValue属性,如果将returnValue设置为false,就会取消默认行为的处理。在超链接的onclick里面禁止访问href的页面。在表单校验的时候禁止提交表单到服务器,防止错误数据提交给服务器、防止页面刷新。(οnsubmit="window.event.returnValue=false;")
  • window.event.returnValue不兼容火狐浏览器

例1:提交表单时,验证用户名是否为空,为空则取消提交动作。

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>北京欢迎你</title>

    <script type="text/javascript">

        function btn_click() {

            var txt = document.getElementById("txt").value;

            if (txt.length == 0) {

                alert("请输入用户名!");

document.getElementById("txt").focus();//文本框获得光标

                window.event.returnValue = false;

            }

        }

    </script>

</head>

<body>

    <form action="HTMLPage2.htm">

    <input id="txt" type="text" />

    <br />

    <input id="Submit1" type="submit" value="submit" οnclick="btn_click()" />

    </form>

</body>

</html>

例2:判断超链接能否跳转

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>北京欢迎你</title>

    <script type="text/javascript">

        function link_click(a) {

            if (a) {

            }

            else {

                alert("无权限")

                window.event.returnValue = false;

            }

        }

    </script>

</head>

<body>

    <a id="link" href="HTMLPage2.htm" οnclick="link_click(0)">hjijiodhoih</a>

</body>

</html>

  • FireFox:e. preventDefault();取消事件的默认动作。
  • 直接写return false;IE、FF、Chrome都可以。需要动态注册事件才可以实现。

例1: <html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>北京欢迎你</title>

    <script type="text/javascript">

        window.onload = function() {

            document.getElementById("Submit1").onclick = function() {

                var txt = document.getElementById("txt").value;

                if (txt.length == 0) {

                    alert("请输入用户名!");

                    document.getElementById("txt").focus(); //文本框获得光标

                    return false;

                }

            }

        }

    </script>

</head>

<body>

    <form action="HTMLPage2.htm">

    <input id="txt" type="text" />

    <br />

    <input id="Submit1" type="submit" value="submit" />

    </form>

</body>

</html>

例2:让超链接无效

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>北京欢迎你</title>

    <script type="text/javascript">

        window.onload = function() {

            document.getElementById("link").onclick = function() {

                return false;

            }

        }

    </script>

</head>

<body>

    <a id="link" href="HTMLPage2.htm">hjijiodhoih</a>

</body>

</html>

//在FF下的写法

        function bodyClickHandlerOnFF(e) {

            if (e.altKey) {

                alert('按下alt键');

            } else {

                alert('普通点击!');

            }

        }

<body οnclick=“bodyClickHandlerOnFF(event);">

//在IE下的写法

        function bodyClickHandler() {

            if (window.event.altKey) {

                alert('press alt key');

            } else {

                alert('normal click');

            }

        }

<body οnclick=“bodyClickHandler();">

=========================兼容的写法===============================

 <script type="text/javascript">

        document.body.onmousemove = function () {

            if (window.event) {

                document.title = '(' + window.event.clientX + ',' + window.event.clientY + ')';

            } else {

                document.title = '(' + arguments[0].clientX + ',' + arguments[0].clientY + ')';

            }

        }

 </script>

  1. window.event的属性(接上页):
    • srcElement:获得事件源对象。几个按钮共享一个事件响应函数用。****_click(object sender,EventArgs e)//IE、Chrome支持。见备注1。//FF下用e.target;

IE下:

 function MyEventHandler() {

            var obj = window.event.srcElement;

            alert(obj.value);

 }

<input type="button" value="click me!" οnclick="MyEventHandler();" />

FF下:

        function MyEventHandlerFF(e) {

            var obj = e.target;

            alert(obj.value);

        }

<input type="button" value="FF Click me" οnclick="MyEventHandlerFF(event);" />

//IE and FF

 function TNB(e) {

            if (e.target) {

                alert(e.target.value);

            } else if (e.srcElement) {

            alert(e.srcElement.value);

            }

  }

    • button,发生事件时鼠标按键,IE:1为左键,2为右键,4中滑轮//要测试event.button的值的时候,请在onmousedown事件中测试。在onclick事件中只能识别鼠标左键的单击。不同浏览器返回值可能不一样。 (不同浏览器值不一样)

              <script type="text/javascript">     

              function mousedown()

              {

                 alert(event.button);

              }

    </script>

  <input id="Button1" type="button" value="/" οnmοusedοwn="mousedown()"/>

    • 除IE浏览器外,其他浏览器在绑定事件处理函数时,有一个默认的参数即event对象。
  1. (*)screen对象,获取屏幕的信息:

alert("分辨率:" + screen.width + "*" + screen.height);

        if (screen.width < 1024 || screen.height < 768) {

           alert("分辨率太低!");

        }

  1. clipboardData对象,对粘贴板的操作。//只支持IE,FF参考资料
    • setData("Text",val),设置粘贴板中的值。

例:

<script type="text/javascript">     

        function f1()

        {

            var t = document.getElementById("txt").value;

            window.clipboardData.setData("text", t);

        }

</script>

<body>

    <input id="txt" type="text" value="http://www.qiushibaike.com"/>

    <input id="Button1" type="button" value="复制" οnclick="f1()"/>

</body>

    • getData(“Text”)读取粘贴板的值,返回值为粘贴板中的内容;
    • clearData(“Text”)清空粘贴板;
    • 案例:复制地址给友好。见备注。
    • 当复制的时候body的oncopy方法被触发,直接return false就是禁止复制。<body οncοpy="alert('禁止复制!');return false;"
    • 很多元素也有oncopy(复制)、onpaste(粘贴)事件:oncut
    • 案例:禁止粘贴帐号。

<input type="text" id="num1" οncοpy="alert('禁止复制'); return false;" οndrag="return false"/><br/>

  <input type="text" οnpaste="return false;" οndrag="return false"/>

    • 案例:在网站中复制文章的时候,为了防止那些”拷贝党”不添加文章来源,代码:

<script type="text/javascript">     

        function ff()

        {

            var t = clipboardData.getData("text");

            t = t + "<br/> 版权:www.srtc.org.cn";

            clipboardData.setData("text", t);

        }

</script>

<body οncοpy="setTimeout('ff()',100)">

    <span>shiusdhfiusdhuihfiusdh</span>

</body>

用户复制动作发生0.1秒以后再去改粘贴板中的内容。100ms只是一个经常取值,写1000、10、50、200……都行。不能直接在oncopy里修改粘贴板。不能直接在oncopy中执行对粘贴板的操作,因此设定定时器,0.1秒以后执行,这样就不再oncopy的执行调用栈上了。

  1. history操作历史记录。

window.history.back()后退;window.history.forward()前进。

window.history.go(-1)后退、window.history.go(1)前进

  1. document属性:
    • document属性是window对象中最复杂的属性。
    • 因为使用window对象成员的时候可以省略window.,所以一般直接写document。
    • document的方法:
      • write();//向文档中写入内容。writeln(),和write差不多,只不过最后添加一个回车。在onclick等事件中写的代码会冲掉页面中的内容,只有在页面加载过程中write才会与原有内容融合在一起。writeln()是在源代码里面换行。与<br/>不一样。
      • document.write()经常在广告代码、整合资源代码中被使用。
      • 内容联盟、广告代码、cnzz,不需要被主页面的站长去维护内容,只要被嵌入的js内容提供商修改内容,显示的内容就变了。例:

write经常在广告代码、整合资源代码中被使用

广告代码的例子:在http://heima8.com/注册一个账户(测试用 账户名:itcast0710 密码:123456),申请一个广告代码,然后放到页面中

整合资源的例子:百度新闻 http://news.baidu.com/newscode.html

百度新闻代码相当于页面中嵌入另外一个网站的js文件,js文件就是一个大的write语句,这样的好处就是主页面不用写死内容,被嵌入的js内容变了嵌入的内容就变了。

脚本的好处:

1.自动执行

2.动态生成。

=================example==================

<script type="text/javascript">

        var reffer = "";

        var url = "";

        if (window.parent != window.self) {

            try { reffer = parent.document.referrer; }

            catch (err) { reffer = document.referrer; }

            try { url = parent.document.location; }

            catch (err) { url = document.location; }

        } else { reffer = document.referrer; url = document.location; }

        document.writeln("<iframe marginwidth='0' marginheight='0' frameborder='0' bordercolor='#000000' scrolling='no' src='http://pv.heima8.com/index.php?p=126292971&b=100002856&itemid1=107075271&reffer=" + escape(reffer) + "&url=" + escape(url) + "' width='468' height='60'></iframe>");

    </script>

      • (使用pre标签看write()与writeln()的区别,效果)。例:

<script type="text/javascript">

    document.write('<pre>');

document.write('1');

document.writeln('2');

document.write('3');

document.write('</pre>');

</script>

      • 最基本的DOM遍历演示。

//遍历直接子节点,如需获得所有节点。需要放在页面的最后测试(或者是在onload里面,否则页面还没有加载完毕。)

 var objHtml = document.documentElement;

 for (var i = 0; i < objHtml.childNodes.length; i++) {

   alert(objHtml.childNodes[i].nodeName);

 }

      • getElementById(), (非常常用),根据元素的Id获得对象,网页中id不能重复。也可以直接通过元素的id来引用元素,但是有有效范围、form1.textbox1之类的问题(当元素放在form中的时候(在html页面中需要通过form.元素id)),因此不建议直接通过id操作元素,而是通过getElementById。

注:如果在网页中有id重复的元素,那么getElementById()获得的是

            //第一id为指定id的元素,而不是数组

            var txtctrl = document.getElementById('txt1');

      • getElementsByName(),根据元素的name获得对象,由于页面中元素的name可以重复,比如多个RadioButton的name一样,因此getElementsByName返回值是对象数组。
      • getElementsByTagName(),获得指定标签名称的元素数组,比如getElementsByTagName(“p”)可以获得所有的<p>标签。*表示所有标签。
      • 此处切忌不要使用forin循环(forin循环循环的是键值对,不是对象本身。)。(问题多多:radio时有相同的key,第一个key是length等等。。)建议:使用for循环案例:实现checkbox的全选,反选
  • 案例:点击一个按钮,被点击的按钮显示“呜呜”,其他按钮显示“哈哈”。

第一种写法

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>北京欢迎你</title>

 

    <script type="text/javascript">

        function g() {

            var strls = document.getElementsByName("11");

            for (var i = 0; i < strls.length; i++) {

                strls[i].value = "哈哈";

            }

            window.event.srcElement.value = "呜呜!!"

        }

     

    </script>

</head>

<body>

    <input id="Button1" type="button" name="11" value="button" οnclick="g()" />

    <br />

    <input id="Button2" type="button" name="11" value="button" οnclick="g()" />

    <br />

    <input id="Button3" type="button" name="11" value="button" οnclick="g()" />

    <br />

    <input id="Button4" type="button" name="11" value="button" οnclick="g()" />

</body>

</html>

第二种写法

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

    <script type="text/javascript">

        window.onload = function () {

            var inputs = document.getElementsByTagName("input");

            for (var i = 0; i < inputs.length; i++) {

                if (inputs[i].type == "button") {

                    inputs[i].onclick = function () {

                      

                        for (var i = 0; i < inputs.length; i++) {

                            if (inputs[i].type == "button") {

                                inputs[i].value = "哈哈";

                            }

                        }

                        //触发事件的对象

                        event.srcElement.value = "呜呜";

                    }

                }

            }

        }

    </script>

</head>

<body>

    <input type="button" value="哈哈" /><br />

    <input type="button" value="哈哈" /><br />

    <input type="button" value="哈哈" /><br />

    <input type="button" value="哈哈" /><br />

    <input type="button" value="哈哈" /><br />

    <input type="button" value="哈哈" /><br />

    <input type="button" value="哈哈" /><br />

    <input type="button" value="哈哈" /><br />

    <input type="text" value="" /><br />

    <input type="text" value="" /><br />

    <input type="text" value="" /><br />

    <input type="text" value="" /><br />

</body>

</html>

  • 练习:加法计算器。两个文本框中输入数字,点击【=】按钮将相加的结果放到第三个文本框中。

    <input type="text" id="num1" />+<input type="text" id="num2" />

    <input type="button" οnclick="calc()" value="=" /><input type="text" id="num3" />

        function calc() {

            var s1 = document.getElementById("num1").value;

            var s2 = document.getElementById("num2").value;

            var i3 = parseInt(s1) + parseInt(s2);

            document.getElementById("num3").value = i3;

        }

  • 案例:十秒钟后协议文本框下的注册按钮才能点击,时钟倒数。(btn.disabled = “” ,让元素可用。disabled=disabled,为不可用)disabled=true;

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>北京欢迎你</title>

 

    <script type="text/javascript">

        var count = 10;

        var tmrId = setInterval("test()", 1000);

        function test() {

            var btn = document.getElementById("btn");

            if (count > 0) {

                btn.value = "请仔细阅读(" + count + ")秒";

                count--;

            } else {

            btn.value = "同意";

            btn.disabled = false;

            clearInterval(tmrId);

            }

        }

        window.onload = function() {

            test();

        }

    </script>

</head>

<body>

    <input id="btn" type="button" value="请仔细阅读(10)秒" disabled="disabled" />

</body>

</html>

  • 练习:图片浏览器。

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

    <script type="text/javascript">

        window.onload = function () {

            var ul = document.getElementById("mv");

            //获取ul中的a标签

            var links = ul.getElementsByTagName("a");

            for (var i = 0; i < links.length; i++) {

                links[i].onclick = function () {//注册事件

                    var href = event.srcElement.href;

                    document.getElementById("i1").src = href;

                    return false;

                }

            }

        }

    </script>

</head>

<body>

    <ul id="mv">

        <li><a href="images/1.jpg">美女1</a></li>

        <li><a href="images/2.jpg">美女2</a></li>

        <li><a href="images/3.jpg">美女3</a></li>

        <li><a href="images/4.jpg">美女4</a></li>

    </ul>

    <br />

    <img id="i1" src="" />

</body>

</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值