html笔记

字数 4761 · 2018-11-23

#web

Elements

html

The root of an HTML document.

metadata

head, title, base, link, meta, style

sections

grouping

text-level

HTML semantic elements

IE8不支持
移动端支持良好

  • section
  • article
  • aside
  • header
  • footer
  • nav
  • figure
  • figcaption
  • time
  • mark
  • main

Partial support refers to missing the default styling, as technically the elements are considered “unknown”. This is easily taken care of by manually setting the default display value for each tag.

Example:

1
2
3
4
5
6
7
8
9
<body>
  <header>
    <nav></nav>
  </header>
  <aside></aside>
  <main>
    <footer></footer>
  </main>
</body>

picture

1
2
3
4
5
<picture>
  <source type="image/svg+xml" srcset="pyramid.svg">
  <source type="image/webp" srcset="pyramid.webp"> 
  <img src="pyramid.png" alt="regular pyramid built from four equilateral triangles">
</picture>

Global attributes

Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements.

  • The basic HTML global attributes
  • xml:lang and xml:base (deprecated)
  • The multiple aria-* attributes
  • The event handler attributes

basic HTML global attributes
class, contenteditable, data-*, dir, draggable, hidden, id, itemid, itemprop, itemref, itemscope, itemtype, lang, spellcheck, style, tabindex, title

Events

In general, we can distinguish events of different kinds based on the object emitting the event including:

  • the window object, such as due to resizing the browser,
  • the window.screen object, such as due to changes in device orientation,
  • the document object, including the loading, modification, user interaction, and unloading of the page,
  • the objects in the DOM (document object model) tree including user interactions or modifications,
  • the XMLHttpRequest objects used for network requests, and
  • the media objects such as audio and video, when the media stream players change state.

Some notable events are:
window: load, resize
document: DOMContentLoaded
DOM node: click

Media events

使用 <audio><video> 时可以使用 play pause 等事件。

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events

iframe

Inline Frame

src - The URL of the page to embed.

1
2
// 判断当前窗口是否在一个Frame中
window.top === window.self
  • window.top
  • window.perent
  • window.self

通信

1
2
3
4
5
6
window.addEventListener('message', (msg)=>{
  // ...
});

// targetWindow 将会收到此条消息
targetWindow.postMessage({/* message */}, '*');

form

  • action
  • method

Input

type

  • text
  • password
  • checkbox
  • radio
  • file
  • button
  • submit

name
The input’s name, to identify the input in the data submitted with the form’s data


<input type="text">
<input> elements of type text create basic single-line text fields.

<input type="submit">
When the click event occurs , the user agent attempts to submit the form to the server.

value attribute contains a DOMString which is displayed as the button’s label.

If you choose to use <button> elements to create the buttons in your form, keep this in mind: if there’s only one <button> inside the <form>, that button will be treated as the “submit” button.


<input type="button">
A push button with no default behavior.

label

for - value is the same as the input’s id

You can click the associated label to focus/activate the input.

Alternatively, you can nest the <input> directly inside the <label>, in which case the for and id attributes are not needed because the association is implicit:

1
2
3
<label>Do you like peas?
  <input type="checkbox" name="peas">
</label>

textarea

a multi-line plain-text editing control.

select

1
2
3
4
5
6
<select id="pet-select">
  <option value="">--Please choose an option--</option>
  <option value="dog">Dog</option>
  <option value="cat">Cat</option>
  <option value="hamster">Hamster</option>
</select>

button

represents a clickable button, which can be used in forms or anywhere in a document that needs simple, standard button functionality.

type

  • submit - The button submits the form data to the server. (Default)
  • reset - The button resets all the controls to their initial values.
  • button - The button has no default behavior.

HTMLFormElement

The HTMLFormElement interface represents a <form> element in the DOM.

Properties
HTMLFormElement.elements - A HTMLFormControlsCollection holding all form controls belonging to this form element.

The elements which are included by HTMLFormElement.elements and HTMLFormElement.length are:

  • <button>
  • <fieldset>
  • <input>
  • <select>
  • <textarea>

Methods

submit()

reset()

Obtaining a form element object
querySelector()

or:

1
2
3
4
5
document.forms[index];
// Returns the form whose ID is id.
document.forms[id];
// Returns the form whose name attribute's value is name.
document.forms[name];

map & area

ARIA

Accessible Rich Internet Applications (ARIA) 规定了能够让 Web 内容和 Web 应用对于残障人士更易使用的各种机制。

XSS

Cross-site scripting

1
<script>alert(document.cookie)</script>
1
<img src="javascript:alert('XSS')">

SVG

Scalable Vector Graphics

1
<svg width="200" height="200" viewBox="0 0 100 100">

Basic shapes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" standalone="no"?>
<svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg">

  <rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>
  <rect x="60" y="10" rx="10" ry="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>

  <circle cx="25" cy="75" r="20" stroke="red" fill="transparent" stroke-width="5"/>
  <ellipse cx="75" cy="75" rx="20" ry="5" stroke="red" fill="transparent" stroke-width="5"/>

  <line x1="10" x2="50" y1="110" y2="150" stroke="orange" stroke-width="5"/>
  <polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145"
      stroke="orange" fill="transparent" stroke-width="5"/>

  <polygon points="50 160 55 180 70 180 60 190 65 205 50 195 35 205 40 190 30 180 45 180"
      stroke="green" fill="transparent" stroke-width="5"/>

  <path d="M20,230 Q40,205 50,230 T90,230" fill="none" stroke="blue" stroke-width="5"/>
</svg>

Paths

The shape of a path element is defined by one attribute: d. The "d" attribute contains a series of commands and parameters used by those commands.

Each of the commands is instantiated by a specific letter.

All of the commands also come in two variants. An uppercase letter specifies absolute coordinates on the page, and a lowercase letter specifies relative coordinates.

SVG defines 6 types of path commands, for a total of 20 commands:

  • MoveTo: M, m
  • LineTo: L, l, H, h, V, v
  • Cubic Bézier Curve: C, c, S, s
  • Quadratic Bézier Curve: Q, q, T, t
  • Elliptical Arc Curve: A, a
  • ClosePath: Z, z

Svg Symbol

Instead of using <g> to wrap all the icon shapes, use <symbol>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<svg style="display: none;">
  <!-- this is our svg sprite -->
  <symbol viewBox="0 0 24 24"
          id="heart">
    <path fill="#E86C60"
          d="M17,0c-1.9,0-3.7,0.8-5,2.1C10.7,0.8,8.9,0,7,0C3.1,0,0,3.1,0,7c0,6.4,10.9,15.4,11.4,15.8 c0.2,0.2,0.4,0.2,0.6,0.2s0.4-0.1,0.6-0.2C13.1,22.4,24,13.4,24,7C24,3.1,20.9,0,17,0z"></path>
  </symbol>
  <symbol viewBox="0 0 32 32"
          id="arrow">
    <!-- ... -->
  </symbol>
</svg>
<svg>
  <!-- this is our visible icon -->
  <use xlink:href="#heart" />
</svg>

https://www.w3cplus.com/svg/how-to-create-an-icon-system-using-svg-symbols.html
https://css-tricks.com/svg-symbol-good-choice-icons/

IntersectionObserver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let intersectionObserver = new IntersectionObserver(
  function(changes) {
    changes.forEach((change) => {
      const el = change.target;
      if (change.intersectionRatio > 0.25) {
        intersectionObserver.unobserve(el);
        console.log('el exposed');
      }
    });
  }, {
    delay: 16,
    threshold: [0, 0.25, 0.5, 0.75, 1],
  }
);
intersectionObserver.observe(el);

MutationObserver

Drag

Making an element draggable requires adding the draggable attribute:

Dragable

1
<p draggable="true">Dragable</p>
1
2
3
4
5
[draggable] {
    user-select: none;
    -webkit-user-drag: element;
    cursor: move;
  }

Drag Events

  • dragstart - fired when the user starts dragging an element or text selection.
  • drag - fired every few hundred milliseconds as an element or text selection is being dragged by the user.
  • dragenter - fired when a dragged element or text selection enters a valid drop target.
  • dragleave - fired when a dragged element or text selection leaves a valid drop target.
  • dragover - fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds).
  • drop - fired when an element or text selection is dropped on a valid drop target.
  • dragend - fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).

DataTransfer

dataTransfer is set in the dragstart event and read/handled in the drop event.

Calling e.dataTransfer.setData(format, data) will set the object’s content to the mimetype and data payload passed as arguments.

dataTransfer also has a getData(format) for fetching the drag data by mimetype.

https://www.html5rocks.com/en/tutorials/dnd/basics/

Selection

1
2
var s = window.getSelection();
s.toStriong()
1
2
3
4
5
r = new Range();
r.selectNode($0);
s = getSelection();
s.removeAllRanges();
s.addRange(r);
  • anchor - The anchor of a selection is the beginning point of the selection.
  • focus - The focus of a selection is the end point of the selection.

一个 selection 可以包括 0 个或者多个 ranges, 仅 firefox 允许选中多个 ranges.

  • elem.onselectstart – when a selection starts on elem.
  • document.onselectionchange – whenever a selection changes, can be set only on document.

  • getRangeAt(i) – get i-th range, starting from 0.
  • addRange(range) – add range to selection.
  • removeRange(range) – remove range from the selection.
  • removeAllRanges() – remove all ranges.
  • empty() – alias to removeAllRanges

Range

The Range interface represents a fragment of a document that can contain nodes and parts of text nodes.

  • deleteContents() – remove range content from the document
  • extractContents() – remove range content from the document and return as DocumentFragment
  • insertNode(node) – insert node into the document at the beginning of the range
  • surroundContents(node) – wrap node around range content.

Selection in form controls

Form elements, such as input and textarea provide special API for selection, without Selection or Range objects.

  • input.select() – selects everything in the text control
  • input.setRangeText(replacement, [start], [end], [selectionMode]) – replace a range of text with the new text.

Audio

In HTML5, there are 3 supported audio formats: MP3, WAV, and OGG.

The <source> element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.

The text between the <audio> and </audio> tags will only be displayed in browsers that do not support the <audio> element.

1
<audio src="/assets/audio/hello.mp3" controls></audio>

Video

1
2
3
4
<video controls preload="metadata">
  <source src="/assets/video/test.mp4" type="video/mp4">
  Not Support.
</video>

The content inside the opening and closing <video></video> tags is shown as a fallback in browsers that don’t support the element.

Attributes

  • autoplay
  • controls
  • muted
  • playsinline
  • poster
  • preload
  • src

Events

  • ended
  • play
  • pause
  • playing
  • progress
  • loadeddata - The first frame of the media has finished loading.
  • loadedmetadata - The metadata has been loaded.

FileReader

1
<input id="file-input" type='file' accept="application/json" hidden/>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function importJson(file) {
    const fileReader = new FileReader();
    fileReader.onload = function ($event) {
        try {
            const data = JSON.parse($event.target.result);
            console.log(data);
        } catch (e) {
            console.log(e);
        }
    };
    fileReader.readAsText(file);
}

const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', () => importJson(fileInput.files[0]));

IndexedDB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var db;
var dbName = 'db1';
var request = window.indexedDB.open(dbName);
request.onerror = function (event) {
  console.err(event);
};
request.onsuccess = function (event) {
  console.log('success');
  db = request.result;
};
request.onupgradeneeded = function (event) {
  console.log('upgrade');
  db = event.target.result;
  var objectStore;
  if (!db.objectStoreNames.contains('person')) {
    objectStore = db.createObjectStore('person', { keyPath: 'id' });
  }
}

// Create
var request = db.transaction(['person'], 'readwrite')
  .objectStore('person')
  .add({ id: 1, name: 'Sue', age: 24, email: 'sue@example.com' });

// Read
var request = db.transaction(['person']).objectStore('person').get(1);
request.onsuccess = function( event) {
  console.log(request.result)
};

// Read All
var objectStore = db.transaction('person').objectStore('person');
objectStore.openCursor().onsuccess = function (event) {
  var cursor = event.target.result;

  if (cursor) {
    console.log(cursor.key, cursor.value);
    cursor.continue();
  } else {
    console.log('end');
  }
};

// Update
var request = db.transaction(['person'], 'readwrite').objectStore('person')
  .put({ id: 1, name: 'lily', age: 35, email: 'lily@example.com' });
request.onsuccess = function (event) {
  console.log('updated');
};

// Delete
var request = db.transaction(['person'], 'readwrite').objectStore('person').delete(1);
request.onsuccess = function (event) {
  console.log('deleted');
};

window.performance

performance property returns a Performance object, which can be used to gather performance information about the current document.

  • mark
  • measure
  • clearMarks
  • clearMeasures

SpeechSynthesis

controller interface for the speech service.

Web Components

  • Custom Elements
  • Shadow DOM
  • HTML Template
1
2
3
4
5
6
class TranslateTooltip extends HTMLElement {
  constructor() {
    super();
  }
}
customElements.define('translate-tooltip', TranslateTooltip);
1
2
3
this.attachShadow({mode: 'open'});
const container = document.createElement('div');
this.shadowRoot.append(style,container);

Lifecycle

  • connectedCallback - Invoked each time the custom element is appended
  • disconnectedCallback
  • adoptedCallback
  • attributeChangedCallback

Node.isConnected

CSSOM

1
2
3
4
5
<div class="container">
<div class="progress"></div>
Hello CSSOM<span class="text"></span>
<button id="btn-run">RUN</button>
</div>
1
2
3
4
.container .progress {
  height: 8px;
  margin: 8px 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const style = document.createElement('style');
document.head.append(style);

let progress = 0;

function prgoressUp() {
  let textEl = document.querySelector('span.text');
  if (progress < 100) {
    progress = progress + 0.1;
    document.styleSheets[0].rules[0].style['background-size']=`${progress}%`
    setTimeout(() => {
      prgoressUp();
    }, 16);
  }
}

document.querySelector('#btn-run').onclick = () => {
  progress = 0;
  prgoressUp();
};

document.styleSheets[0].insertRule(`
  .progress {
    background-size: 0%;
    background-repeat: no-repeat;
    background-image: linear-gradient(65deg, #ff4594, #ff8426 66%, #ff4594);
    -webkit-text-fill-color: transparent;
  }
`);

A2HS

  • manifest file, linked from the HTML head
  • icon
  • a Service Worker registered
  • served over HTTPs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "background_color": "white",
  "description": "Hello World",
  "display": "standalone",
  "icons": [
    {
      "src": "/assets/github_192.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ],
  "name": "Github IO",
  "short_name": "IO",
  "start_url": "/search/index.html"
}

Service Worker

Only run over HTTPS

  • Register
  • Download
  • Install
  • Activate

use case:

  • pre-fetching resources
  • timed task

Updating

  • byte-diff

CacheStorage

  • open()
  • match()
  • keys()
  • has()
  • delete()

Cache

  • add()
  • addAll()
  • delete()
  • keys()
  • match()
  • matchAll()
  • put()

WorkBox

  • generateSW
  • injectManifest

Caching Strategies

  • Stale While Revalidate
    • Cache First + Update Background
  • Network First
    • Use cache when request failed or offline
  • Cache First
  • Network Only
  • Cache Only

Plugin

  • cacheWillUpdate
    • Called before a Response is used to update a cache
    • return null can avoid updating the cache
  • cacheDidUpdate
    • new entry is added to a cache
    • existing entry is updated
  • cacheKeyWillBeUsed
    • Called before a request is used as a cache key
  • cachedResponseWillBeUsed
  • requestWillFetch

  • fetchDidFail
  • fetchDidSucceed

  • handlerWillStart
  • handlerWillRespond
  • handlerDidRespond
  • handlerDidComplete
  • handlerDidError

https://developer.chrome.com/docs/workbox/using-plugins/

IE

conditional comments

As of IE 10, conditional comments are no longer supported by standards mode.

1
2
3
<!--[if IE 8]>
<p>Welcome to Internet Explorer 8.</p>
<![endif]-->

SEO

robots.txt
sitemap.xml

CROS

历史上表单一直可以发出跨域请求

非简单请求,浏览器会向服务器发出预检请求 OPTIONS

由服务端控制 Access-Control-Allow-Origin

History

1
history.replaceState(stateObj, '', 'bar2.html');

JSONP

<script> 元素不受同源策略的限制

1
2
<script type="text/javascript" src="https://example.com/jsonp">
</script>

响应的内容为可执行的 JS

1
parseResponse({name: 'JSONP'});

Refs

Can I use… Support tables for HTML5, CSS3, etc