Introduction to Java Web (V) - HTML-CSS-Javascript Foundation

Keywords: Javascript Attribute Java IE

Introduction to Java Web (V) - HTML/CSS/Javascript Foundation

Label (Space Separation): Java Web

Original address

DTD Document Model and HTML Foundation

<!doctype html>

HTML5 is the most popular document model at present.

The Meaning of Common Labels

<meta charset= "utf-8"> indicates that the encoding character set of the specified document is utf-8.

<m eta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

viewport is used to configure some parameters of user entry, mainly for setting the scaling ratio of mobile terminal, width is specified as the width of the device, maximum-scale is used to specify the scaling ratio, when specified as 1.0, it means that scaling is not allowed.

Semantically

Semanticization means that when we use html tags, we should pay attention to choosing appropriate tags to express them. This way of writing will make our html structure clear and logical, which greatly facilitates reading and maintenance in the future.

  • <h1>- < H5 > denotes the title, and its importance and size decrease in turn.
  • <p> Represents a paragraph, so using < br > to force line breaks within the P tag is semantically incorrect.
  • Strong > denotes important text.
  • <em> Text expressing emphasis.
  • The < I > tag denotes a paragraph of Italic text, but is now commonly used to denote an icon.

Commonly used labels

Develop a good habit of writing more comments to make html hierarchical.

Such as:

<!-- header -->
<header class="header">

</header>
<!-- header end -->

Such annotations apply to scenarios where clear structure cannot be seen directly through html elements.

The alt and title attributes in the picture label.

<img alt="The picture cannot be displayed for the time being." title="National flag">

The alt attribute is the image displayed when the image cannot be displayed, while the title is the text displayed when the mouse hovers.

The target attribute of the a tag is used to indicate how the link is opened:

  • _ blank opens in a new window.
  • _ self opens in the original window.

The < hr/> label is a horizontal dividing line.

< ol > is a sequential list. (ordered list)

< UL > is an unordered list. (unorderd list)

< Table > table

<tr> one line
<td> A cell
< th > header cells
rowspan attributes are merged rows
The colspan attribute is a merged column

Generally, tables can be designed with tools such as DreamWeaver, but tables are rarely used to represent tables.

The < iframe > tag represents the inline framework and can be understood as the browser in the browser.

form control

Note: All form controls should be placed in the <form></from> tab.

control Explain
< select > Select
< checkBox > Checkbox
< checkBoxGroup > Grouping of multiple check boxes
< radio > radio button
< radioGroup> Single selection group
< textarea> Large area of text
< input type="file"> Upload files
< fieldset> Grouping development controls
< input type="hidden" > input control invisible, but can be passed to the background
< input type="image"> Picture button

HTML5 Improved input Element

Input type="tel"> <input type="number"> Input of number type and telephone type, however, the support is not good.

< input required > indicates that the input box must be filled in.

< input autofocus > denotes autofocus.

<label for="input_name"> indicates that when you click on the label text, you focus on the control input_name.

CSS Foundation

Three methods of using css

  1. In-line Style\
    <table style="font-size: 20px;">
  2. The internal style is written in the < head > tag
    <style type="text/css"></style>
  3. External style
    <link rel="stylesheet" type="text/css" href="">

CSS Selector

Six common selectors

  • tag chooser
table {
    color: red;
}

Styles of all table s on the page

  • Class selector
.btn{
    line-height: 15px;
}

Styles of all BTN classes < input class= "btn">

  • ID Selector
#navBtn{
    bgcolor: "orange";
}

Style <input id="navBtn"> denoting ID as navBtn

  • Descendant inheritance selector
.container table{
    margin: 0px;
}

Represents the style of all table s under class container

  • Group Selectors
.container .wrapper{
    padding: 0px;
}

Represents the styles that both container and wrapper classes have

  • attribute selectors
input[type="text"]{
    color: red;
}

Represents the style of the input space in which the type attribute is text.

  • Pseudo-class selector
a:link{color: #FF0000;} /*Style of Unaccessed Links*/
a:visited{color: #00FF00}   /*Links that have been visited, such as red in baidu search results*/
a:hover{color: #FF00FF} /*Mouse Hover Style*/
a:active{color: ##0000FF} /*After clicking*/
p:before/after{ /*Insert content before/after each p element and style the inserted content*/
    content:"Lines:-";
    background-color:yellow;
    color:red;
    font-weight:bold;
}

Priority of CSS selector

Importance > Inline > Id > Class > Properties

CSS Core Model

  • Floating float

The original elements are separated from the normal document flow and arranged left and right. Without setting the width, the width will become the minimum width. If a div is set to float, the width will be minimized and not the whole line.

It's like queuing to buy tickets when someone suddenly flies up and rides around someone else's neck.

  • Location position

Relative: relative positioning, refers to the position after the offset is still in place, in situ also occupies the document stream, offset is relatively in situ.

Abslute: After the offset, the in-situ location disappears. The elements are separated from the document stream and migrated by locating the elements that are absolute or relative in the nearest parent container. Generally, the parent elements are not located by using absolute/relative, so they are offset from the whole document < body >.

fixed: fixed location, no matter how the browser scrolls, the location remains unchanged.

static: Default location, that is, document flow location.

  • line-height

Nor: Default Reasonable Line Height

Number: Sets a number that multiplies the current font size

length: Fixed row spacing

% Based on the percentage of the current size

inherit: inherits from parent node

  • Horizontal, Vertical Centralization

text-align: center text centered

margin-left:auto;margin-right:auto; also middle

valign: middle vertically centered
Align: the cell td commonly used for table s at middle level

Example: Using div to simulate table cell centering

.outer{
    display: table;
}
.inner{
    display: table-cell;
    vertival-align: middle; /*Vertical centering*/
}

Note: If the width and height of an element are set to be very large, then its width is limited by the parent element, while its height is not limited.

Example: How to center a div relative to the parent element?

.middle_div{
    width: 200px;
    height: 200px;
    top: 50%;
    left: 50%; /*Center the top left of the box, where 50% is relative to the parent element.*/
    margin-left: -100px;
    margin-top: -100px; /*Set margin-top and margin-left to - 0.5 * height and - 0.5 * width to ensure the center of the box*/
    position: absolute; /*Absolute positioning, in-situ positioning disappears, we need to pay attention to the parent element to positon: absolute / relationship, otherwise relative to the entire page in the middle*/
}

CSS Box Model

Default elements have their own margin and padding. If you need to remove the default before development, you need the following code:

*{
    margin: 0;
    padding: 0;
}

Standard/Weird Box Model

Standard Box Model (W3C Box Model):

The width or height of W3C box model is calculated by width/height = content.

Weird Box Model (IE Box Model is generally used for mobile end layout):

The widths or heights of the weird box model are calculated as width/height = content + padding + border.

If we calculate the length, width and height of a box, we usually calculate the thickness of the box itself and the size of the space in the box. The IE box model and the W3C box model are where we are, we will find that the IE box model is more logical.

We use a CSS3 attribute box-sizing:content-box | border-box | inherit. The default value is content-box standard box model. The width or height of the box only limits the width and height of the content. The actual width or height of the box is the width of the content + padding value + border value. If the value is border-box, then the element is a weird box model. The width and height of the box limit the size of the box and are not affected by padding and border.

If the page as a whole uses the standard/weird box model, the following styles are required.

*{
    -webkit-box-sizing: content-box;    //Compatible with chrome and safari
    -moz-box-sizing: content-box;       //Compatible with mozilla browser
    box-sizing: content-box;
}
  • overflow is a useful property that specifies how to use content in a box when it exceeds the size of the box.
  • overflow: hidden denotes the over-part hiding, and overflow: scroll denotes that the over-part can be scrolled with a scroll bar.

CSS Elastic Box Model

Double-wing configuration

Javascript Foundation

Javascript is a dynamic, weak-typed, prototype-based, interpretative language.

Variable type

Js variables are weakly typed, and all variables are objects, that is, everything is objects.

But you can also view specific types through typeof().

There are generally the following types:

Type name Explain
number number
string Character string
boolean Boolean value
object object
array array
function function
undefined Undefined

Statements of the above variables:

var x = 123;    //typeof(x):number
x = "Zhang Sanfeng";   //typeof(x):string
x = ture;       //typeof(x):boolean
x = ["sunny""Xin Qiji"1.618];  //typeof(x): object
x = function(x, y){
    //...
}
var y;  //Typeof (y): type when undefined is not assigned

Introduction of js file

  • js in the page
<script type="text/javascript">
    console.log("Hello Js!");
</script>
  • External js
<script type="text/javascript" src="../script/jquery.min.js"></script>

Nomenclature of Variables and Functions

Hump nomenclature: myName, getData;

switch statement

switch(true){
    case score <= 60 && score >= 50:
        level = "c";
        break;
    case score > 60 && score <= 80:
        level = "b";
        break;
    case score > 80 && case <= 100:
        level = "c";
        break;
    default:
        break;
}
//The above wording is often used to simplifyif else Sentence

//casePenetrating usage

switch(true){
    case score >= 60:
    case score >= 70:
        rate = "pass";
        break;
    //Types and OR operations in if
    //if(score >= 60 || score >= 70)
}

Strings and arrays

var str = "hello";
alert(str.length);  //The length attribute is the length of the string

var ret = parseInt(str);    //The parseInt global method is used to convert a string to an integer
ret = parseFloat(str);      //parseFloat is used to convert a string to a floating-point type

console.log(str.charAt(1)); //The charAt method is used to get characters at a particular position in a string, and can only be used for string types.

str.substring(4,9);
str.substring(9,4); //Both of them have the same effect (4,9)/(9,4) from the fourth character of the string (subscript from 0) to intercept five characters before the ninth position.

str.substr(4,9);    //Substr intercepts a string of specified length from the specified position. The result here is that the character substr of 9 after 4 is not in the standard and is not recommended for use.

str.slice(4,9);     //The slice method is also used to take strings between the start position and the end position. The parameters can be negative u numbers. When the negative number is, the position is calculated forward from the end of the string.

str.slice(-3);      //That is to say, three characters at the end of the string are taken. If the end position is not specified, the end position is the end by default.

str.indexOf("he");       //Look back and forth for the first place where a substring appears
str.lastIndexOf("ll");  //Look for the first place where a substring appears before you think about it. Return - 1 if not found

str.trim();     //Remove the spaces on both sides of the string

var matches = "fat,sat,cat".match("at");
matches.index;   // 1
matches.input;   // "fat,sat,cat"

str.replace("l", "p");  //heplo, just replace the first matched substring
str.replace(/l/g, "p"); //ReplceAll can be achieved by using regular/g global matching

var strArray = "hello|javascript|hahah".split("|");  //Divide the string and return the string array hello, javascript, hahah ah

strArray = "hello|java|script".split("|", 2);   //Divide the string and return an array length of 2, hello,java

var arr = new Array(4); //Object declaration, using the new keyword

var arr = ["Xiaodong"3, "Da Hong"]; //The definition of an array, defined by [], {} represents an object
var obj = {name: "Da Hong", age: 28};

arr[1] = [0,1,2];   //Arrays can be nested in arrays. At this time, the structure of arrays becomes ["Xiaodong", "Array", "macro"]. Array [1] [0] can be used to access arrays in arrays.

arr.length; //At this point, the array length is still 3 because typeof([0,1,2]) is an object.


Array object

var a = [1,2,3];
a.toString();   //"1,2,3"

a.push(4);  //Add an element at the end of the array and return the length of the array to 4, similar to the stacked LIFO

a.pop();    //The element at the end of the pop-up, similar to the stack

a.join("||");   //Assemble each element of an array with | as an spacer as a string 1 | | 2 | | 3
a.join();       //When there are no parameters, it is used by default, splicing and returning "1,2,3"

a.concat(b);    //Returns two connected arrays a and B

a.shift();      //Delete and return the first element of the array, similar to the queue, FIFO
a.unshift("1");    //Insert an element at the head of the array to return the length of the array

a.slice(1,3);   //Returns the subarray [2,3] slice(start, end);
a.slice(-2);    //Returns a subarray of the last two elements [2,3]

a.splice(index, howmany, item1,...,itemx);  //For adding/deleting items in an array, return deleted items: index specifies the location of deletion/addition, Howman specifies the number of deleted items, item selection, new items added to the array
a.splice(1,2);  //Delete two items from one location
a.splice(1,0,4);    //Do not delete items from 1 location, add an item 4

a.sort();   //Sorting each item in an array in character order changes the array itself.

//New Array Method in ecmascript 5.0
arr.map(callback[,thisArg]);    //callback is automatically passed in three parameters: the array element, the element index, and the original array itself.
a = [1,4,9];
var roots = a.map(Math.sqrt);   //The map method returns a new array consisting of the return value of each element of the original array after calling a specified method. The above code can find the square root of each element in the array [1, 2, 3].

arr.filter(callback[,thisArg]);
//The filter method returns a new array of elements that each element of the original array conforms to the specified filtering rules.
var filtered = arr.filter(function(ele){
    return ele > 2;
})
//At this time, each element will be filtered, and elements that conform to the filtering rules form a new array as the return value [4,9].

arr.some(callback[,thisArg]);
//some method calls a conditional function for each element and returns true as long as one condition is satisfied.
function isBiggerThan10(element, index, array){
    return element > 10;
}

[1,2,11].some(isBiggerThan10);  //true
[1,2,3,,6,8].some(isBiggerThan10);  //false

arr.every(callback[,thisArg]);
//every method calls a conditional function for each element and returns true only if all elements satisfy the condition.

[11,12,13,5,15].every(isBiggerThan10);  //false
[12,51,52,43,15].every(isBiggerThan10); //true

arr.reduce(callback,[initialValue]);
//The reduce method applies a function (left to right) to each value of the accumulator and array to reduce it to a single value.
//Callback is a function that executes each value in the array, with four parameters accumulator: the value returned by the last call callback
//Or provide the initial value initialValue;currentValue: the element being processed in the array; currentIndex: the index being processed in the array; array: the array calling reduce.
var sum = [0,1,2,3,4].reduce(function(a,b){
    return a + b;
}, 0);`
//sum result is 10
var flattened = [[0,1],[2,3],[4,5]].reduce(function(a.b){
    return a.concat(b);
}, []);
//flattened results were [0,1,2,3,4,5].

arr.reduceRight(callback,[initialValue]);   //Same reduction, but from right to left

JS objects and functions

var obj = {
        name : "Micheal Scofield",
        age : 28,
        "function" : "blank",   //Membership attributes can be quoted and keywords can be used
        "print" : function(prefix){ //Member method
            console.log( prefix + "\nName: " + this.name + "\nAge:" + this.age + "\nGender:" + this.gender);
        } 
    };
    obj["location"] = "Fox River";  //Add member
    console.log(obj);
    console.log(Object.keys(obj));  //Returns all member keys, similar to keyset in map
    obj.print("Hello javascript");

NUMERICAL TYPES AND MATHEMATICAL FUNCTIONS

All values in Javascript are 64-bit floating-point decimals.

There are errors in the calculation of Js median, so we should be careful about the exact operation, such as 0.3/0.1 = 2.999999999996.

NaN denotes non-numeric value, it is a value, but NaN!= NaN, it is not equal to any value, to determine whether non-numeric value to use the isNaN(value) method

NaN boolean operations as false, with 0, null, undefined, NaN, ""

isNaN(NaN) is true, which is the only true case.

console.log(0.3/0.1);   //2.999999999996
console.log(isNaN(NaN));    //ture
console.log(isFinite(Infinity));    //false

clog(parseInt("2.11")); //2
clog(parseInt(".3"));   //NaN
clog(parseFloat(" 3.141582653e5")); //314158.2653
clog(Number("3.5"));    //Force String to Number

function clog(v){
    console.log(v);
}

Mount on Prototype

Number.prototype.huawen = "test";   //Mount a huawen member on the prototype of Number object
var t = new Number("1");
clog(t.huawen); // test
Object.prototype.huawen = "Decorative pattern";   //Mount a huawen member on the prototype of all objects

Mathematical function

Constants: Math.E Math.PI

Common methods:

Math.round(3.5);
Math.round("3.5");  //Rounding 4
Math.abs(-3);   //3 absolute value
Math.min(1,2,3);    // 1 Find the minimum
Math.min([1,2,3]);  //NaN cannot pass arrays
Math.max(1,2,3);    //3 Find the maximum
Math.min.apply(null, [1,2,3]);  //You can take each element in an array as a parameter
Math.floor(3.7);   //Floor function, lower bound integer 3 
Math.ceil(3.1);     //Ceiling function, upper bound integer 4
Math.random();      //Returns a number in [0,1] interval, which is a pseudo-random number (regular random number)

JS event stream

The concept of event flow: Accept the order of events in a page.

  1. Event bubbles:

It is received by the most specific element and then uploaded to the least specific element node step by step. (document)

  1. Event capture

The least specific elements are first received and then transferred down to the most specific elements step by step.

event processing

  1. DOM Level 0 Event Handling: Copy a function to an event handler property.

example

var btn = document.getElementById("btn");
btn.onclick = function(){
    alert("CLICK");
}
btn.onclick = null;

The disadvantage of this method is that it can only bind unique functions for event handler attributes and override previous bindings when multiple bindings occur.

  1. DOM2 event handling

addEventListener("Event Name", Event Handler, true/false);
When true, the event flow is captured, from outside to inside, while when false, it is bubbling, from inside to outside. Default false.
removeEventListner("Event Name", Event Handler, true/false)

example

btn.addEventListener("click", fun1);
btn.addEventListener("click", fun2);    //Binding two processing functions for click time

//A Compatibility Time Processing
if(btn.addEverntListener()){
    btn.addEventListener("click", fun1);
}else if(btn.attachEvent()){
    btn.attachEvent("onclick", fun1);
}else { 
    btn.onclick = fun1;
}

Event object

When a DOM event is triggered, an object is generated: event, which has the following common attributes:

Type: Event type
Target: Event target
CurrtTarget: Current Target

Target is in the target phase of event flow; current Target is in the capture, target and bubbling phase of event flow.
The two directions are the same only when the event flow is in the target phase, while in the capture and bubbling phase, the target points to the clicked object and the current Target points to the object of the current event activity (usually the parent).

stopPropagation(): Prevent event bubbles
preventDefault(): Prevents default behavior of events

example

var btn1 = document.getElementById('btn').addEventListener('click', showType);
function showType(event){
    console.log(event.type);
    console.log(event.target);
    console.log(event.currentTarget);
}

Posted by Eric T on Mon, 01 Apr 2019 10:45:29 -0700