<form>
<input type="text" id="user" autofocus>
form>
<script>
// 之前传统js自动聚焦的方法
// document.getElementById('user').focus()
script>
<header>header>
<nav>nav>
<section>section>
<main>main>
<article>article>
<aside>aside>
<footer>footer>
<section>
<h1>PRCh1>
<p>The People's Republic of China was born in 1949...p>
section>
<article>
<header><h1>计算机各类语言介绍h1>header>
<p>本文列举了部分计算机语言的一些介绍p>
<section>
<h2>JavaScripth2>
<p>js是一门……p>
section>
<section>
<h2>HTMLh2>
<p>HTML是一门……p>
section>
<footer>版权所有footer>
article>
DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
X-UA-Compatible确实是为了我们定义浏览器的渲染方式的;
如果存在客户端Chrome Frame并启用,那么浏览器访问页面会被Chrome内核渲染
(这一点没太大意义,因为你开发的项目不能要求用户在客户端来安装Chrome Frame);也就是说IE浏览器变身Chrome是可以的,但前提是客户端安装了Chrome Frame,呵呵;
使用IE内核浏览器来访问,会渲染至该浏览器的最高版本,比如你使用IE9浏览器,那么就算在兼容模式切换至IE7,但仍会渲染成IE9的样子(当然IE7浏览器是不会渲染成IE9的,不然想想都好美丽)。
比如现在我在客户端装了Chrome Frame,然后我的IE浏览器是IE11,也就是说我服务器端已经设置了X-UA-Compatible属性的值为IE=edge,chrome=1,客户端已经安装并启用Chrome Frame。我现在用IE浏览器打开指定网页。
竟然在IE浏览器下看到了审查元素,而且点击审查元素出现了在Chrome下几乎一样的控制台
https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/meta
https://www.cnblogs.com/dreamaker/p/10576750.html
http-equiv顾名思义,相当于http的文件头作用,它可以向浏览器传回一些有用的信息,以帮助正确和精确地显示网页内容,与之对应的属性值为content,content中的内容其实就是各个参数的变量值。
引用
meat标签的http-equiv属性语法格式是:<meta http-equiv=“参数” content="参数变量值"> ;其中http-equiv属性主要有以下几种参数:
<head>
<meta charset="UTF-8">
head>
charset 属性是 HTML5 中的新属性,且替换了:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
仍然允许使用 http-equiv 属性来规定字符集,但是使用新方法可以减少代码量。
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=0" />
<p>选中,checked属性只要存在,就会选中,无论其值是什么p>
<input type="checkbox" checked>
<input type="checkbox" checked="true">
<input type="checkbox" checked="checked">
<input type="checkbox" checked="false">
<p>未选中p>
<input type="checkbox">
<big> HTML5不再支持。 定义大号文本。
<center> HTML5不再支持。 HTML 4.01 已废弃。定义居中文本。
<font> HTML5不再支持。 HTML 4.01 已废弃。 定义文本的字体、尺寸和颜色
<strike> HTML5不再支持。 HTML 4.01 已废弃。 定义加删除线的文本。
<frame> HTML5不再支持。 定义框架集的窗口或框架。
<frameset> HTML5不再支持。定义框架集。
<noframes> HTML5不再支持。 定义针对不支持框架的用户的替代内容。
<iframe> 定义内联框架。这个仍旧支持
使用 data-* 属性来嵌入自定义数据:
data-* 属性由以下两部分组成:
js获取dataset
// 获取data-*属性值
// 1. 按照普通属性获取
document.getElementsByTagName('div')[0].getAttribute('data-myattr')
// 2. 通过dom.dataset
document.getElementById('demo2').dataset.myattr
/* hello 不生效 */
div[myattr='myattrname'] {
width: 80px;
height: 40px;
background: pink;
}
/* hello 生效 */
div[data-myattr='myattrname'] {
width: 80px;
height: 40px;
background: pink;
}
拖放是 HTML5 中非常常见的功能。
在拖动目标上触发事件 (源元素):
释放目标时触发的事件:
// 目标元素开始拖动
document.addEventListener("dragstart", function (event) {
//dataTransfer.setData()方法设置数据类型和拖动的数据
event.dataTransfer.setData("Text", event.target.id);
});
// ........
// 拖动区域鼠标释放目标元素
document.addEventListener("drop", function (event) {
event.preventDefault();
if (event.target.className == "droptarget") {
var data = event.dataTransfer.getData("Text");
event.target.appendChild(document.getElementById(data));
// 将目标元素放在在拖拽容器
}
});
在Web应用中,实现动画效果的方法比较多,JavaScript 中可以通过定时器 setTimeout 来实现,css3 可以使用 transition 和 animation 来实现,html5 中的 canvas 也可以实现。除此之外,html5 还提供一个专门用于请求动画的 API,即 requestAnimationFrame(rAF),顾名思义就是 “请求动画帧”。
http://caibaojian.com/requestanimationframe.html
requestAnimationFrame:优势:由系统决定回调函数的执行时机。60Hz的刷新频率,那么每次刷新的间隔中会执行一次回调函数,不会引起丢帧,不会卡顿
requestAnimationFrame使用一个回调函数作为参数。这个回调函数会在浏览器重绘之前调用。
requestID = window.requestAnimationFrame(callback);
function myAnimate(){
// 动画代码
// 动画降频
requestAnimationFrame(myAnimate)//再次设置下次浏览器重绘之前的动画事件
}
requestAnimationFrame(myAnimate)//下一次浏览器重绘之前调用myAnimate
// 通过requestID可以取消
http协议是无状态的
cookies,session HTML4存储 会话跟踪
//获取
var cookieAll = document.cookie;
console.log(cookieAll);
//存储Cookie
let username = 'Javan';
document.cookie = "name=" + username; //只能逐条追加cookie,相同key名会覆盖
// 过期时间
document.cookie = 'name=xiaoxiong;max-age=30' //30s后cookie过期删除
var d = new Date();
d.setDate(d.getDate()+10) //10天后过期
document.cookie = 'name=xiaoxiong;expires='+d
// 'name=xiaoxiong;expires=Thu Jan 13 2022 08:34:15 GMT+0800 (中国标准时间)'
// 设置过期时间进行删除
let exp = new Date()
exp.setTime(exp.getTime() - 1);
document.cookie= "test=xiao;expires=" + exp.toGMTString();//格林威治时间,比exp少8个小时
@WebServlet("/testServlet")
public class testServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response){
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
String[] bookNames = request.getParameterValues("book");
response.sendRedirect(request.getContextPath()+"/shopping/step-2.jsp");
}
}
//jsp 中获取session String[] bookNames = (String[])session.getAttribute("bookNames");
HTML5 Web 存储(localStorage和sessionStorage)
HTML5 Web 存储(webStorage)是本地存储,存储在客户端,包括localStorage和sessionStorage。
HTML5 Web 存储是以键/值对的形式存储的,以字符串形式存储。
history.back() = history.go(-1)
history.forward() = history.go(1)
history.length
history.pushState()
// pushState只会在当前history中添加一条记录,地址栏发生变化,但不会加载网页
history.pushState({name:'xx'}, "my title", "/test.html")
history.state //获取
history.replaceState()
// replaceState会替换当前的history中的记录,并且刷新浏览器
history.replaceState({}, "my title", "/test.html")
原生js——操作类名(HTML5新增classList)
URL
为指定的脚本。web workers 是html5提供的一个JavaScript多线程解决方案
我们可以将一些大计算量的代码交由web worker运行而不冻结用户界面
但是子线程完全受主线程控制,且不能操作dom
所以这个新标准并没有改变JavaScript单线程的本质
<p>计数: <output id="result">output>p>
<button onclick="startWorker()">开始工作button>
<button onclick="stopWorker()">停止工作button>
<script>
var w;
function startWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
//Worker 加载分线程中的js文件
}
//向分线程发生消息
w.postMessage('hello')
//绑定接收分线程返回的消息
//回调代码必须在初始化之后才可以进行,所以它的位置没有要求
w.onmessage = function(event) {
//event.data 接收的数据
console.log('主线程接收到的分线程的数据',event.data)
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "抱歉,你的浏览器不支持 Web Workers...";
}
}
function stopWorker()
{
w.terminate();
w = undefined;
}
script>
分线程demo_workers.js 文件代码
//分线程接收到主线程的数据
var message = function(event){
//不能用函数声明
console.log('分线程接收到主线程的数据',event.data)
}
//复杂计算
var i=0;
function timedCount()
{
i=i+1;
postMessage(i);
//分线程向主线程发送数据
//postMessage也可以是主线程向分线程发送消息,他们是互相的
//onmessage 同理
setTimeout("timedCount()",500);
}
timedCount();
https://www.cnblogs.com/leejersey/p/4772504.html
FileReader
对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据。
事件处理
WebSocket 对象提供了用于创建和管理 WebSocket 连接,以及可以通过该连接发送和接收数据的 API。
构造函数
WebSocket()构造函器会返回一个 WebSocket 对象。
var aWebSocket = new WebSocket(url [, protocols]);
事件和对应属性
使用 addEventListener() 或将一个事件监听器赋值给本接口的 oneventname 属性,来监听下面的事件。
方法
常量
https://socket.io/
在线聊天室
场景: 股票交易系统、多人聊天室 、前后端实时系统、服务器消息推送、、
HTML5只专注于客户端的API, 而服务器端是各个语言自己去实现
WebSocket的服务端和客户端可以双向进行通讯,并且允许跨域通讯。
function success(e){
console.log('获取位置成功',e)
}
function failure(e){
console.log('获取位置失败',e)
}
window.navigator.geolocation.getCurrentPosition(success,failure)
// 谷歌浏览器中当允许获取位置时,因为电脑没有gps,所有会去从谷歌地图获取,需要科学上网
// edge浏览器中可以正常获取
DeviceOrientation将底层的方向传感器和运动传感器进行了高级封装,提供了DOM事件的支持。
这个特性包括两个事件:
if (window.DeviceMotionEvent) {
window.addEventListener("devicemotion", function(event) {
// DeviceMotionEvent.acceleration 只读
// 提供了设备在X,Y,Z轴方向上加速度的对象。加速度的单位为 m/s2
// DeviceMotionEvent.accelerationIncludingGravity 只读
// 提供了设备在X,Y,Z轴方向上带重力的加速度的对象。加速度的单位为 m/s2
console.log(event.acceleration.x + ' m/s2');
}, true);
}
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", function(event) {
//alpha范围 0-360 beta -180至180 gamma -90至90
// alpha: 在Z轴上的角度
var rotateDegrees = event.alpha;
// alpha为0°时表示设备的顶部正指北极方向,当设备向左旋转时,alpha将增加。
// gamma: 从左到右
var leftToRight = event.gamma;
// beta: 从前到后的运动
var frontToBack = event.beta;
handleOrientationEvent(frontToBack, leftToRight, rotateDegrees);
}, true);
}
这是一个很好的设计啊!那它和延迟有什么关系呢? 我们假定一个场景。当用户看到一张图片,而此时图标又刚好是一个链接地址。用户点击到图片之后,并不能立即判断用户是要打开链接,还是说想观看图片的细节。因此Safari 就等待300毫秒,判断用户是否再次点击了屏幕。这也是会有上述 300 毫秒延迟的主要原因。
由于iPhone的这一成功,许多浏览器厂商开始支持这一功能。但是随着技术的发展,性能的提升。慢慢的出现了混合开发,web应用在某些场景一开始逐渐替代了原生开发。此时所有的单击事件都有300毫秒延迟,必然是不可接受的,那怎么去解决这个问题呢?
解决
<meta name="viewport" content="user-scalable=no">
<meta name="viewport" content="initial-scale=1,maximum-scale=1">
有一个小小的缺点需要说一下,由于图片和文字都是一比一的比例显示的,而且禁用了缩放功能。在某些情况下,需要放大某张图片或者某段文字,就是无法实现图片的双击放大了。(除非js脚本)
<meta name="viewport" content="width=device-width">
这个方法跟方法一有些许不一样,他将页面的宽度设置成了,与显示屏同宽。需要网站做响应式布局。否则显示效果极易受到影响。还有他没有禁止缩放功能,所以,你可以用双指操作来放大页面。
html {
touch-action: none
}
这是个CSS属性,如果值为 none 的话, 就表示禁用掉该元素上的浏览器代理的任何默认行为(缩放,移动, 拖拽),无300ms延迟。你也可以在html标签上面设置该属性,虽然该方法实现了禁用缩放。但是其他的触摸类型交互事件都被禁用了。导致页面无法滚动。
fetch(url, config)
返回一个Promise对象。
fetch 函数返回一个 Promise 对象。
Response 对象:
Request 对象 new Request(url地址,配置)
https://developer.mozilla.org/zh-CN/docs/Web/API/fetch
请注意,fetch 规范与 jQuery.ajax() 主要有以下的不同
const config = {
method: "GET",
// headers: {
// "Content-Type": "application/json",
// a: 1
// }
}
const req = new Request(url, config);
try{
const resp = await fetch(req);
const pro = await resp.json();
console.log(pro);
}catch(err) {
console.log(err);
}
fetch('http://localhost/index.html')
.then(response => response.text())
.then(data => console.log(data));
// es6
const result = await fetch(url, config);
const respText = await result.text();
fetch('http://localhost/test.json')
.then(response => response.json())
.then(data => console.log(data));
const result = await fetch(url, config);
const respJson = await result.json();
fetch('http://localhost/test.jpg')
.then(response => response.blob())
.then(data =>{
var img = new Image();
img.src = URL.createObjectURL(data); // 这个data是blob对象
document.body.appendChild(img);
}
);
const result = await fetch(url, config);
const respBlob = await result.blob();
fillRect(x, y, width, height)
strokeRect(x, y, width, height)
clearRect(x, y, width, height)
fillText(text, x, y [, maxWidth])
strokeText(text, x, y [, maxWidth])
drawImage
图片绘制
drawImage(image, dx, dy)
drawImage(image, dx, dy [, dWidth, dHeight])
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
<style>
#canvas{
border: 1px solid #000;
}
style>
<body>
<canvas id="canvas" width="300" height="180">canvas>
body>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 1. 画填充矩形
ctx.fillStyle = 'orange';//背景色
ctx.fillRect(50,50,100,100);
// 2. 画透明矩形 清除
ctx.clearRect(75,75,50,50);
// 3. 画边框矩形
ctx.strokeStyle = 'red';//边框颜色
ctx.strokeRect(50,50,80,80)
script>
const img= new Image();
img.onload = function(){
const pattern = ctx.createPattern(img,'no-repeat');
//const pattern = ctx.createPattern(canvas2,'no-repeat'); //canvas2作为图片源
ctx.fillStyle = pattern;
ctx.fillRect(0,0,400,300);
}
img.src = 'http://visitjapan-photocontest2016.people.cn/NMediaFile/2017/0112/MAIN201701121021000257100783409.jpg'
const img= new Image();
img.onload = function(){
ctx.drawImage(img,20,20,300,200)
}
img.src = 'https://gitee.com/jingyu7/pic/raw/master/202201041158200.jpeg'
const dataURL=canvas.toDataURL('image/jpeg'); //转换图片为dataURL
ctx.font = '50px sans-serif';
ctx.fillText('Hello World',10,50)
ctx.strokeText('Hello World',10,100)
绘制其他形状均需要路径
beginPath()
closePath()
stroke()
fill()
moveTo(x, y);
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(50,50); //起始点
ctx.lineTo(100,100);//线 终止点
ctx.lineWidth= 10; //线宽
ctx.stroke()
ctx.beginPath();
ctx.moveTo(30,30);
ctx.lineWidth = 20;
ctx.lineCap = 'round';
ctx.lineTo(150,30);
ctx.stroke()
ctx.beginPath();
ctx.moveTo(30,200);
ctx.lineWidth = 20;
ctx.lineJoin = 'bevel';
// round
ctx.lineTo(150,30);
ctx.lineTo(200,200);
ctx.stroke()
ctx.lineWidth=5;
// ctx.lineJoin="miter";
ctx.miterLimit=5;
ctx.moveTo(20,20);
ctx.lineTo(50,27);
ctx.lineTo(20,34);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.lineWidth= 5; //线宽
ctx.moveTo(50,50); //起始点
ctx.lineTo(150,70);//线 终止点
ctx.lineTo(100,100);//线 终止点
ctx.closePath(); //闭合路径 最后一个点和第一个点连接
ctx.stroke()
// 曲线从moveTo()指定的点开始: (20, 110)。 控制点位于(230, 150)。 曲线在(250, 20)处结束。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(20, 110);
ctx.quadraticCurveTo(230, 150, 250, 20);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(50,20);
ctx.bezierCurveTo(230, 30, 150, 60, 50, 100);
ctx.stroke();
ctx.fillStyle = 'blue';
// start point
ctx.fillRect(50, 20, 10, 10);
// end point
ctx.fillRect(50, 100, 10, 10);
ctx.fillStyle = 'red';
// control point one
ctx.fillRect(230, 30, 10, 10);
// control point two
ctx.fillRect(150, 70, 10, 10);
ctx.translate(x, y);
设置canvas原点;默认原点在左上角ctx.save()
将当前状态放入栈中,保存canvas全部状态的方法。ctx.restore()
还原到上次保存的默认状态ctx.scale(x,y)
如果您对绘图进行缩放,所有之后的绘图也会被缩放。定位也会被缩放。ctx.rotate(angle);
旋转
ctx.transform(a, b, c, d, e, f);
ctx.setTransform(a, b, c, d, e, f);
重新设置(覆盖)当前的变换并调用变换的方法
//
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 50, 50);
ctx.save(); // 暂存当前的状态
ctx.fillStyle = "orange";
ctx.fillRect(150, 75, 100, 100);
ctx.restore(); //还原到上次保存的状态 fillStyle = "green
ctx.scale(2,2);//放大到 200%再绘制:
ctx.fillRect(40, 10, 50, 50);
ctx.fillStyle = "red";
ctx.scale(0.5,0.5)
// 缩放到初始大小
// 如果您对绘图进行缩放,所有之后的绘图也会被缩放。定位也会被缩放。
ctx.rotate(45 * Math.PI / 180);
ctx.fillRect(70,0,100,100);
// 旋转之后的绘图也会被旋转。
ctx.rotate(-45 * Math.PI / 180);
ctx.fillStyle = "black";
ctx.transform(1,1,0,1,300,0);
ctx.fillRect(0,0,100,100);
ctx.fillStyle = "yellow";
// ctx.transform(1,1,0,1,300,0); //这个会叠加上次的transform变换
ctx.setTransform(1,1,0,1,300,0); //不会叠加上次的transform变换
ctx.fillRect(10,10,50,100);
// const gradien = ctx.createLinearGradient(0,0,300,300) //45度渐变
const gradien = ctx.createLinearGradient(0,0,300,0) //x方向渐变
gradien.addColorStop(0,'lightblue');
gradien.addColorStop(0.5,'lightpink');
gradien.addColorStop(1,'orange')
ctx.fillStyle = gradien;
ctx.fillRect(0,0,300,300)
ctx.shadowColor = 'black';
ctx.shadowOffsetX = 25;
ctx.shadowOffsetY = 15;
ctx.shadowBlur = 15; //模糊半径
ctx.fillStyle = 'red';
ctx.fillRect(0,0,150,100)
ctx.globalAlpha = 0.2; //透明度
// ctx.globalAlpha = 0.2; //透明度
ctx.beginPath();
ctx.arc(100,100,80,0,2*Math.PI,false)
// ctx.fill()//填充
ctx.stroke()//描边
ctx.clip();//剪贴
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,100,100)
canvas.toDataURL('image/jpeg');
也有此问题Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(10,10,50,50);
function copy(){
var imgData=ctx.getImageData(10,10,50,50);
ctx.putImageData(imgData,10,70);
}
//
https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
设置图像重叠部分的处理
canvas 是位图放大会失真,SVG为了解决这个问题,SVG是矢量图
可缩放矢量图形(Scalable Vector Graphics,SVG),是一种用于描述二维的矢量图形,基于 XML 的标记语言
元素的渲染顺序。SVG文件全局有效的规则是“后来居上”,越后面的元素越可见。
web上的svg文件可以直接在浏览器上展示,或者通过以下几种方法嵌入到HTML文件中:
SVG文件类型:推荐使用“.svg”(全部小写)作为此类文件的扩展名。
基本形状
常用应用场景:小图标,边框动画,图片加文字
Flash player 插件 安全问题-> HTML5提供的音视频接口