JAVAScript learning 3 - DOM

Through the HTML DOM, access to all the elements JavaScript HTML document.

DOM can be doing?

    JavaScript can change page for all HTML element
    JavaScript can change the properties of all HTML pages
    JavaScript can change all CSS styles page
    JavaScript can react to all events page

When the page is loaded, the browser will create a page of a document object model (Document Object Model).
HTML DOM model is constructed as an object tree:

 

image.png

Find element method:

    1, a direct lookup:

    getElementByid (): id find HTML elements by
    getElementsByTagName (): find HTML elements (list) through the label name
    getElementsByClassName (): find HTML elements (list) by the class name

    getelementsByName (): find HTML elements (list) by name property

    2. Indirect find:

    parentNode parent node
    childNodes all child nodes
    firstChild The first child node
    lastChild The last child node of a
    next sibling node nextSibling
    on a sibling node previousSibling
    parentElement parent tag element
    children of all sub-tabs
    firstElementChild first child tag element
    lastElementChild last child element tag
    nextElementtSibling next sibling label elements
    on a previousElementSibling brothers label elements

    3, add and delete nodes and elements:


Methods of operation:

    innerText text, splicing all the text of the specified ID, remove HTML elements spaced
    outerText write mode, replace all child elements
    innerHTML creates a new DOM tree according to the specified value, and then use the DOM tree completely replace invocation elements originally all the children node.
    outerHTML the write mode, new elements in the DOM tree replace the original
    value property sets or returns the default value of the password field. Gets the value of the text box. 

 

Class attribute operations (CSS stylesheet name):

    Get all the class name className
    classList.remove (cls) Removes the specified class
    classList.add (cls) Add category

checkbox attributes:

    checkbox.checked: true checked, false do not choose

tag label operation:

    1, createElement () to create a label:   

         Each has its own HTML tag attributes, attribute reference: https: //www.w3school.com.cn/jsref/dom_obj_anchor.asp

function append_tag(){
   var a = document.createElement('a')
   var cur = document.getElementById('dd')
   a.innerHTML='click me'
   a.href='http://www.baidu.com'
   a.className='a1'
   cur.appendChild(a)    //添加标签
}
\\----------等同于
var a_tag="<a class='a1' href='>click me</a>"

    2, operation tag:

    

    insertAdjacentText ( 'position', obj) is inserted into the text, if the HTML objects are displayed in the specified place in the form of text out
    insertAdjacentHTML ( 'position', obj) is inserted at the designated place html content

    Location Description:

        beforeBegin: label starting position before (pre tag)

        afterBegin: starting position after the label (the label)

        beforeEnd: End tag (the tag) before the position

        afterEnd: after the label end position (outer tab)

When using a laptop to upload

    3, label style operating style:

var obj = document.getElementById('i1')
obj.style.fontSize = "32px";
obj.style.backgroundColor = "red";

    4, the position of the operation

    document.documentElement.offsetHeight total height of the document
    document.documentElement.clientHeight current document accounting screen height
    tag.offsetHeight own highly
    tag.offsetTop from superior positioning height
    tag.offsetParent parent label positioning
    tag.scrollTop Roll Height

/ * 
    ClientHeight -> visible area: height + padding 
    clientTop -> border height 
    offsetHeight -> visible area: height + padding + border 
    offsetTop -> height of the superior position of the tag 
    scrollHeight -> High entirety: height + padding 
    scrollTop -> scroll highly 
    special of: 
        document.documentElement on behalf of that document root node 
* /

 

event:

    

    addEventListener () method used to add event handlers to the specified element.

    Event handler addEventListener () method to add event handlers are not covered by existing.

    You can add multiple event handlers to one element.

    You can add more of the same type of event handler to the same element, such as: two "click" event.

    You can listen to any DOM object to add an event, not just HTML elements. Such as: window object.

    addEventListener () method can more easily control events (bubbling and capture).

    When you use addEventListener () method, JavaScript HTML tags from left to carve, more readable, in the absence of control HTML tags you can also add event listeners.

    You can use removeEventListener () method to remove an event listener.

    语法:element.addEventListener(event, function, useCapture);

   

    Event Type:

Attributes This event occurs when ... Attributes This event occurs when ...
Onboart Loading the image is interrupted. onload A page or an image has finished loading.
onblur Element loses focus. onmousedown Mouse button is pressed.
onchange The content domain is changed. onmousemove The mouse is moved.
onclick Event when the user clicks on an object called a handle. onMouseOut The mouse is moved off an element.
ondblclick Event when the user double-clicks an object called a handle. onmouseover Move the mouse over an element.
onerror An error occurred while loading a document or image. onmouseup The mouse button is released.
onfocus Element receives the focus. onreset The reset button is clicked.
onkeydown A keyboard key is pressed. OnResize Window or frame is resized.
onkeypress A keyboard key is pressed and released. onselect Text is selected.
onkeyup A keyboard key is released. onsubmit OK button is clicked.
onunload User exits the page.

 Keyboard and mouse events:

Attributes description
altKey Returned when the event is triggered, "ALT" is pressed.
button Returned when the event is triggered, which mouse button is clicked.
clientX Returned when the event is triggered, the horizontal coordinates of the mouse pointer.
clientY When an event is triggered when returning the vertical coordinates of the mouse pointer.
ctrlKey Returned when the event is triggered, "CTRL" key is pressed.
metaKey Returned when the event is triggered, "Meta" key is pressed.
relatedTarget 返回与事件的目标节点相关的节点。
screenX 返回当某个事件被触发时,鼠标指针的水平坐标。
screenY 返回当某个事件被触发时,鼠标指针的垂直坐标。
shiftKey 返回当事件被触发时,"SHIFT" 键是否被按下。

 

小例子:

1、文本框默认文字

<input id="i1" type="text" onfocus="foucs(this)" onblur="blurs(this)" value="请输入关键字"/>
<script>
    function foucs(th){
        var v=th.value;
        if (v=='请输入关键字'){
            th.value='';
        }
    }
    function blurs(th){
        var v=th.value;
        if (v.length==0){
            th.value='请输入关键字';
            th.style.color="gray";
            th.style.border="1px solid red";
        }
    }
</script>

 2、添加标签

<div style="border: 1px solid red;" id="std">
</div>

function b_b(){
    var std=document.getElementById('std');
    var new_b="<input type='button' value='我是beforeBegin,在DIV前' />";
    std.insertAdjacentHTML('beforeBegin',new_b);
}
function a_b(){
    var std=document.getElementById('std');
    var new_b="<input type='button' value='我是afterBegin,在DIV内前' />";
    std.insertAdjacentHTML('afterBegin',new_b);
}
function b_e(){
    var std=document.getElementById('std');
    var new_b="<input type='button' value='我是beforeEnd,在DIV后' />";
    std.insertAdjacentHTML('beforeEnd',new_b);
}
function a_e(){
    
    var std=document.getElementById('std');
    var new_b="<input type='button' value='我是afterEnd,在DIV内后'/>";
    std.insertAdjacentHTML('afterEnd',new_b);
}

 3、展开同时隐藏其它子菜单:

        HTML:

<div id="left_menu" class="left_menu">
    <div id='m1' class="main_menu" onclick="show_sub_menu(this)"><span>人员管理</span></div>
    <div id='sm1' class="sub_menu">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
        </ul>
    </div>

    <div  id='m2' class="main_menu" onclick="show_sub_menu(this)"><span>组别管理</span></div>
    <div id='sm2' class="sub_menu">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
        </ul>
    </div>
</div>

        JS:

function show_sub_menu(th){
    var parentId = th.id;
    var childId='s'+parentId;
    var childE=document.getElementById('left_menu').children;
    for (var s in childE){
        var e=childE[s].classList;
        console.log(e);
        if (e){
            if (childE[s].id==childId){
                childE[s].classList.add('show');
            }else{
                childE[s].classList.remove('show');
            }
         }
    }
}

 4、标签提交:

<!-- DOM提交标单!-->
<form id="f1" action="search.html">
    <input id="input1" type="text"/>
    <a onclick="a_submit()">提交吧</a>
</form>


<script>
    function a_submit(){
        document.getElementById('f1').submit();
    }
</script>

 

 5、html、css、js页面分离:生产环境的写法。

       每类存储为单独的文件,其中js使用dom添加事件方法,可以html更简洁。

例子:鼠标移动表格行变色

    HTML:

<table id='tb'>
    <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
    <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
    <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
    <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
    <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr>
</table>

     JS:给table添加属性和class

    var t=document.getElementById('tb').classList;
    t.add('tb_style');
    
    var mytrs=document.getElementsByTagName('tr');
    var td_numbers=mytrs.length;
    for (var td=0;td<td_numbers;td++){
        mytrs[td].onmouseover=function(){this.style.backgroundColor='red';};
        mytrs[td].onmouseout=function(){this.style.backgroundColor='';};
    }

     css:

.tb_style{
    bacground-color:pink;
}

 6、词法分析:形参--》函数体内函数,编译时函数体内的函数会分配 内存地址,覆盖形参。

function cifa(age){
    console.log(age);        \\function age
    age=22;
    console.log(age);        \\22
    function age(){};
    console.log(age);        \\22
}

age(3)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.51cto.com/yishi/2428833