zoukankan      html  css  js  c++  java
  • javascript学习(二) DOM操作HTML

    一:DOM操作HTML

    1. JavaScript能够改变页面中所有的HTML元素
    2. JavaScript能够改变页面中所有的HTML属性
    3. JavaScript能够改变页面中所有的CSS样式
    4. JavaScript能够对页面中的所有事件做出反应

    • 改变HTML的输出流:document.write(); 会覆盖其他的元素,所以最好不要用

          eg1:简单操作HTML元素和属性

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
        <p id="p1">
            Hello</p>
        <button id="btn" onclick="demo()"></button>
        <button id="Button1" onclick="demo2()">
            覆盖</button>
        <a id="aid" href="www.baidu.com">百度</a>
        <button id="Button2" onclick="demo3()">
            修改元素</button>
        <script type="text/javascript">
            function demo() {
                document.getElementById("p1").innerHTML = "World";
            }
            function demo2() {
                document.write("会覆盖其他元素");
            }
            function demo3() {
                document.getElementById("aid").href = "http://www.cnblogs.com/lipeng0824/";
                document.getElementById("aid").innerHTML = "李鹏的博客";
            }
        </script>
    </body>
    </html>

      eg2:操作样式和监听(包括几种不同的改变(注册)html事件的方法)

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <style>
            #divid
            {
                background-color: Red;
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    <body>
        <div id="divid">
        </div>
        <script>
            var div = document.getElementById("divid");
            //匿名函数修改dom属性
            div.onmousemove = function () {
                div.style.backgroundColor = "yellow";
            };
            //直接修改函数   注意这里的函数名后面没有括号
            div.onmouseout = bian2;
            //为div添加监听函数
            div.addEventListener("click", bian);
            div.addEventListener("click", function () {
                alert("点击了div");
            });
            function bian() {
                div.style.backgroundColor = "blue";
            }
            function bian2() {
                div.style.backgroundColor = "black";
            }
        </script>
    </body>
    </html>

      

      

  • 相关阅读:
    【leetcode】Reverse Words in a String
    使用windows的远程桌面连接连接Ubuntu
    Ubuntu下快速安装php环境
    面试题之【打印1到最大的N位数】
    gnuplot安装问题(set terminal "unknown")
    java获取文件的md5值
    jQuery全选/反选checkbox
    PowerDesigner反向工程,根据Oracle数据库结构生成ER图(2014-3-25记)
    SVN服务端启动解决方案(2013-12-10 记)
    Oracle数据库DOC命令导入导出(2014-3-10记)
  • 原文地址:https://www.cnblogs.com/lipeng0824/p/4414498.html
Copyright © 2011-2022 走看看