2016年9月4日 星期日

javascript 的研究筆記 00

Ref :



<!DOCTYPE html>
<html>
<body>

<p>Creating and using an object method.</p>

<p>A method is actually a function definition stored as a property value.</p>

<p id="demo"></p>

<script>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>


Using Built-In Methods

This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message = "Hello world!";
var x = message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!

Adding New Methods

Defining methods to an object is done inside the constructor function:

Example

function person(firstName, lastName, age, eyeColor) {
    this.firstName = firstName;  
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.changeName = function (name) {
        this.lastName = name;
    };
}

Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon).

Example

function myFunction(a, b) {
    return a * b;
}

Function Expressions

A JavaScript function can also be defined using an expression.
A function expression can be stored in a variable:

Example

var x = function (a, b) {return a * b};

After a function expression has been stored in a variable, the variable can be used as a function:

Example

var x = function (a, b) {return a * b};
var z = x(43);

The Function() Constructor

As you have seen in the previous examples, JavaScript functions are defined with the function keyword.
Functions can also be defined with a built-in JavaScript function constructor called Function().

Example

var myFunction = new Function("a""b""return a * b");

var x = myFunction(43);


Self-Invoking Functions

Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function expression:

Example

(function () {
    var x = "Hello!!";      // I will invoke myself})();


The Arguments Object

JavaScript functions have a built-in object called the arguments object.
The argument object contains an array of the arguments used when the function was called (invoked).
This way you can simply use a function to find (for instance) the highest value in a list of numbers:

Example

x = findMax(11235001154488);

function findMax() {
    var i;
    var max = -Infinity;
    for (i = 0; i < arguments.length; i++) {
        if (arguments[i] > max) {
            max = arguments[i];
        }
    }
    return max;
}

<script>
function findMax() {
    var i;
    var max = -Infinity;
    for(i = 0; i < arguments.length; i++) {
        if (arguments[i] > max) {
            max = arguments[i];
        }
    }
    return max;
}
document.getElementById("demo").innerHTML = findMax(4, 5, 6);
</script>

Or create a function to sum all input values:

Example

x = sumAll(11235001154488);

function sumAll() {
    var i, sum = 0;
    for (i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

JavaScript Form Validation

HTML form validation can be done by a JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:

JavaScript Example

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}


HTML Form Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>

<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>

</body>
</html>


HTML Constraint Validation

HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
  • Constraint validation HTML Input Attributes
  • Constraint validation CSS Pseudo Selectors
  • Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

AttributeDescription
disabledSpecifies that the input element should be disabled
maxSpecifies the maximum value of an input element
minSpecifies the minimum value of an input element
patternSpecifies the value pattern of an input element
requiredSpecifies that the input field requires an element
type Specifies the type of an input element

Constraint Validation CSS Pseudo Selectors

SelectorDescription
:disabledSelects input elements with the "disabled" attribute specified
:invalidSelects input elements with invalid values
:optionalSelects input elements with no "required" attribute specified
:requiredSelects input elements with the "required" attribute specified
:validSelects input elements with valid values



Constraint Validation DOM Methods

PropertyDescription
checkValidity()Returns true if an input element contains valid data.
setCustomValidity()Sets the validationMessage property of an input element.

Changing the Value of an Attribute

To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute=new value
This example changes the value of the src attribute of an <img> element:

Example

<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>

Changing HTML Style

To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:



Using Events

The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
  • An element is clicked on
  • The page has loaded
  • Input fields are changed
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when the user clicks a button:

Example

<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button" 
onclick="document.getElementById('id1').style.color = 'red'"
>

Click Me!</button>

</body>
</html>

<!DOCTYPE html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
</style>
<body>

<p>
<button onclick="myMove()">Click Me</button>
</p>

<div id ="container">
<div id ="animate"></div>
</div>

<script>
function myMove() {
  var elem = document.getElementById("animate");
  var pos = 0;
  var id = setInterval(frame, 5);  //  每5ms 就會呼叫  frame 這個class
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + 'px';   //     更新  top address  
      elem.style.left = pos + 'px';   //     更新  left address
    }
  }
}
</script>



也可以在 script 裡面去指定當按下會發生的事情

Assign Events Using the HTML DOM

The HTML DOM allows you to assign events to HTML elements using JavaScript:

Example

Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>


The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.

Example

<body onload="checkCookies()">

The onchange Event

The onchange event is often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.

Example

<input type="text" id="fname" onchange="upperCase()">



<!DOCTYPE html>
<html>
<body>

<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>

<script>
function mOver(obj) {
    obj.innerHTML = "Thank You"
}

function mOut(obj) {
    obj.innerHTML = "Mouse Over Me"
}
</script>

</body>
</html>


<!DOCTYPE html>
<html>
<body>

<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
    obj.style.backgroundColor = "#1ec5e5";
    obj.innerHTML = "Release Me";
}

function mUp(obj) {
    obj.style.backgroundColor="#D94A38";
    obj.innerHTML="Thank You";
}
</script>

</body>
</html>


The addEventListener() method

Example

Add an event listener that fires when a user clicks a button:
document.getElementById("myBtn").addEventListener("click", displayDate);



The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
You can add many event handlers to one element.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.


Add an Event Handler to an Element

Example

Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click"function(){ alert("Hello World!"); });


you can also refer to an external "named" function:

Example

Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", myFunction);

function myFunction() {
    alert ("Hello World!");
}
Try it Yourself »


Add Many Event Handlers to the Same Element

The addEventListener() method allows you to add many events to the same element, without overwriting existing events:

Example

element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);


<p>This example uses the addEventListener() method to add many events on the same button.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);

function myFunction() {
    document.getElementById("demo").innerHTML += "Moused over!<br>";
}

function mySecondFunction() {
    document.getElementById("demo").innerHTML += "Clicked!<br>";
}

function myThirdFunction() {
    document.getElementById("demo").innerHTML += "Moused out!<br>";
}
</script>


Add an Event Handler to the Window Object

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Example

Add an event listener that fires when a user resizes the window:
window.addEventListener("resize"function(){
    document.getElementById("demo").innerHTML = sometext;
});

Passing Parameters

When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:

<p>This example demonstrates how to pass parameter values when using the
addEventListener() method.</p>

<p>Click the button to perform a calculation.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
var p1 = 5;
var p2 = 7;

document.getElementById("myBtn").addEventListener("click", function() {
    myFunction(p1, p2);
});

function myFunction(a, b) {
    var result = a * b;
    document.getElementById("demo").innerHTML = result;
}
</script>


Event Bubbling or Event Capturing?

There are two ways of event propagation in the HTML DOM, bubbling and capturing.
Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element's "click" event should be handled first?
In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is handled first, then the <div> element's click event.
In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will be handled first, then the <p> element's click event.
With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:
addEventListener(eventfunctionuseCapture);
The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.



The removeEventListener() method

The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:

Example

element.removeEventListener("mousemove", myFunction);

Cross-browser solution:
var x = document.getElementById("myBtn");
if (x.addEventListener) {                    // For all major browsers, except IE 8 and earlier    x.addEventListener("click", myFunction);
else if (x.attachEvent) {                  // For IE 8 and earlier versions    x.attachEvent("onclick", myFunction);
}


From the HTML above you can read:
  • <html> is the root node
  • <html> has no parents
  • <html> is the parent of <head> and <body>
  • <head> is the first child of <html>
  • <body> is the last child of <html>


and:
  • <head> has one child: <title>
  • <title> has one child (a text node): "DOM Tutorial"
  • <body> has two children: <h1> and <p>
  • <h1> has one child: "DOM Lesson one"
  • <p> has one child: "Hello world!"
  • <h1> and <p> are siblings

Child Nodes and Node Values

In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.
The following example collects the node value of an <h1> element and copies it into a <p> element:

Example

<html>
<body>

<h1 id="intro">My First Page</h1>

<p id="demo">Hello!</p>

<script>
var myText = document.getElementById("intro").childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>

</body>
</html>
































沒有留言:

張貼留言