2409js,学习js2

原文

全局对象

function sayHi() {alert("Hello");
}// 全局对象的函数.
window.sayHi();
alert(window.innerHeight);

更改背景

document.body.style.background = "red";setTimeout(() => document.body.style.background = "", 1000);

当前地址

alert(location.href); 
if (confirm("Go to Wikipedia?")) {location.href = "https://wikipedia.org";// 重定向
}

子:childNodes,firstChild,lastChild

elem.childNodes[0] === elem.firstChild
elem.childNodes[elem.childNodes.length - 1] === elem.lastChild
//子们.
for (let node of document.body.childNodes) {alert(node); // 迭代.
}

同级与父级

alert( document.body.parentNode === document.documentElement ); // true
alert( document.head.nextSibling ); // 
alert( document.body.previousSibling );

对于所有节点:parentNode,childNodes,firstChild,lastChild,previousSibling,nextSibling.
仅适用于元素节点:parentElement,children,firstElementChild,lastElementChild,previousElementSibling,nextElementSibling.

取元素

let elem = document.getElementById('elem');
elem.style.background = 'red';

选择器

let elements = document.querySelectorAll('ul > li:last-child');
//支持伪类
for (let elem of elements) {alert(elem.innerHTML); 
}

elem.querySelector返回第1个匹配元素.

elem.matches(css),是否匹配.

for (let elem of document.body.children) {if (elem.matches('a[href$="zip"]')) {alert("哈哈.." + elem.href );}}

elem.closest(css)查找与CSS选择器匹配最近祖先.包含elem.
querySelector更强大,

document.body.innerHTML = 'The new BODY!';
alert(elem.outerHTML); 
// <div id="elem">Hello <b>World</b></div>

文本的兄弟:

let text = document.body.firstChild;
alert(text.data); // Hellolet comment = text.nextSibling;
alert(comment.data); // Comment
alert(news.textContent);//去掉所有标签的纯文本.
elem.hidden = true;//隐藏元素
setInterval(() => elem.hidden = !elem.hidden, 1000);
//闪烁元素.

直接访问属性

alert(elem.type); // "text"
alert(elem.id); // "elem"
alert(elem.value); // value

给节点加元素加方法

document.body.myData = {name: 'Caesar',title: 'Imperator'
};alert(document.body.myData.title); // document.body.sayTagName = function() {alert(this.tagName);
};document.body.sayTagName();

给所有元素加方法

Element.prototype.sayHi = function() {alert(`Hello, I'm ${this.tagName}`);
};document.documentElement.sayHi(); // 
document.body.sayHi(); // 

几个属性方法

elem.hasAttribute(name),检查是否存在属性.
elem.getAttribute(name),获取值.
elem.setAttribute(name,value),设置值.
elem.removeAttribute(name),删除属性.

属性同步

let input = document.querySelector('input');// attribute => propertyinput.setAttribute('id', 'id');alert(input.id); // id (updated)// property => attributeinput.id = 'newId';alert(input.getAttribute('id')); // newId (updated)

不同步

let input = document.querySelector('input');// attribute => propertyinput.setAttribute('value', 'text');alert(input.value); // text// NOT property => attributeinput.value = 'newValue';alert(input.getAttribute('value')); // 未更新.

更改属性值更新属性.
但更改属性不会影响属性.

数据集

<style>.order[data-order-state="new"] {color: green;}.order[data-order-state="pending"] {color: blue;}.order[data-order-state="canceled"] {color: red;}
</style><div id="order" class="order" data-order-state="new">A new order.
</div><script>// readalert(order.dataset.orderState); // new// modifyorder.dataset.orderState = "pending"; // (*)
</script>

elem.attributes是所有属性的集合.

创建元素

let div = document.createElement('div');
let textNode = document.createTextNode('Here I am');
//文本节点,
let div = document.createElement('div');
div.className = "alert";
//设置类.填充内容.
div.innerHTML = "<strong>Hi there!</strong> You've read an important message.";

node.append(...节点或串),在节点末尾附加节点或串,
node.prepend(...节点或串),在节点的开头插入节点或串,
node.before(...节点或串),在node之前插入节点或串,
node.after(...节点或串),在节点后插入节点或串,
node.replaceWith(...节点或串),按给定的节点或串替换node.

ol.before('before');ol.after('after');
ol.prepend(liFirst);
ol.append(liLast);
div.insertAdjacentHTML('beforebegin', '<p>Hello</p>');
div.insertAdjacentHTML('afterend', '<p>Bye</p>');
//插入html
elem.insertAdjacentText(where,text)
//beforebegin,afterbegin,beforeend,afterend
//插入文本
elem.insertAdjacentElement(where,elem)
div.remove()
//删除节点.

所有插入方法都会自动从旧位置删除节点.

克隆节点

let div2 = div.cloneNode(true);//深度
let div2 = div.cloneNode();//非深度

文档片段

function getListContent() {let fragment = new DocumentFragment();for(let i=1; i<=3; i++) {let li = document.createElement('li');li.append(i);fragment.append(li);}return fragment;
}ul.append(getListContent()); // (*)

高级点

function getListContent() {let result = [];for(let i=1; i<=3; i++) {let li = document.createElement('li');li.append(i);result.push(li);}return result;
}ul.append(...getListContent());

旧方法

list.appendChild(newLi);
list.insertBefore(newLi, list.children[1]);
list.insertBefore(newLi, list.firstChild);
list.removeChild(li);
parentElem.replaceChild(节点,oldChild)

风格

elem.style.left = left; 
elem.style.top = top;
alert(document.body.className);
//类名,main page
document.body.classList.add('article');
alert(document.body.className); 
// main page article
for (let name of document.body.classList) //迭代.

方法有:

classList.add/remove
classList.toggle
classList.contains

风格

button.style.MozBorderRadius = '5px';
button.style.WebkitBorderRadius = '5px';

隐藏

document.body.style.display = "none"; // hide
setTimeout(() => document.body.style.display = "", 1000); // 显示.setTimeout(() => document.body.style.removeProperty('background'), 1000);
//删除属性

文本串属性

div.style.cssText=`color: red !important;background-color: yellow;width: 100px;text-align: center;`;alert(div.style.cssText);

单位

document.body.style.margin = '20px';
alert(document.body.style.margin); // 20pxalert(document.body.style.marginTop); // 20px
alert(document.body.style.marginLeft); // 20pxlet computedStyle = getComputedStyle(document.body);
//计算风格.只读.
alert( computedStyle.marginTop ); // 5pxalert( computedStyle.color );

延迟或异步加载

<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script><script async src="https://javascript.info/article/script-async-defer/long.js"></script>
<script async src="https://javascript.info/article/script-async-defer/small.js"></script>

动态脚本

let script = document.createElement('script');
script.src = "/article/script-async-defer/long.js";
document.body.append(script); // (*)

改变监视器

使用MutationObserver,可以检测到在DOM中何时出现不需要的元素,并删除它.
有更改后,执行回调:

let observer = new MutationObserver(callback);
observer.observe(node, config);

例:

<div contentEditable id="elem">Click and <b>edit</b>, please</div>
<script>
let observer = new MutationObserver(mutationRecords => {console.log(mutationRecords); // 记录更改.
});// 除了属性外.
observer.observe(elem, {childList: true, // 观察直接子,subtree: true, // 及子树.characterDataOldValue: true // 旧数据
});
</script>
//
mutationRecords = [{type: "characterData",oldValue: "edit",target: <text node>,// other properties empty
}];

数组缓冲

ArrayBuffer,固定长度连续内存区域引用.

let buffer = new ArrayBuffer(16);
let view = new Uint32Array(buffer);
alert(view.length);//4
alert(view.byteLength); // 16,按字节.
// 赋值.
view[0] = 123456;// 迭代
for(let num of view) {alert(num); // 123456, 然后0, 0, 0 

相同视图

let arr8 = new Uint8Array([0, 1, 2, 3]);
let arr16 = new Uint16Array(arr8.buffer);

任意格式视图

let buffer = new Uint8Array([255, 255, 255, 255]).buffer;
let dataView = new DataView(buffer);
alert( dataView.getUint8(0) ); // 255
alert( dataView.getUint16(0) ); // 65535 
alert( dataView.getUint32(0) ); // 4294967295 
dataView.setUint32(0, 0);

解码二进制

let uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
alert( new TextDecoder().decode(uint8Array) ); // Hello
let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]);
alert( new TextDecoder().decode(uint8Array) ); // 你好

文本编码器

let encoder = new TextEncoder();let uint8Array = encoder.encode("Hello");
alert(uint8Array); // 72,101,108,108,111

let blob = new Blob(["<html>…</html>"], {type: 'text/html'});
//第1参为数组.

动态下载

<a download="hello.txt" href='#' id="link">Download</a>
<script>
let blob = new Blob(["Hello, world!"], {type: 'text/plain'});
link.href = URL.createObjectURL(blob);
</script>

动态链接

let link = document.createElement('a');
link.download = 'hello.txt';
let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
link.href = URL.createObjectURL(blob);
link.click();
URL.revokeObjectURL(link.href);//删除掉

图像操作

let img = document.querySelector('img');
let canvas = document.createElement('canvas');
canvas.width = img.clientWidth;
canvas.height = img.clientHeight;
let context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
//前面是绘画,后面是保存.canvas.toBlob(function(blob) {// 下载let link = document.createElement('a');link.download = 'example.png';link.href = URL.createObjectURL(blob);link.click();URL.revokeObjectURL(link.href);
}, 'image/png');

const readableStream = blob.stream();
const stream = readableStream.getReader();
while (true) {let { done, value } = await stream.read();if (done) {console.log('all blob processed.');break;}console.log(value);
}

取文件

<input type="file" onchange="showFile(this)">
<script>
function showFile(input) {let file = input.files[0];//可选择多个文件.alert(`File name: ${file.name}`); alert(`Last modified: ${file.lastModified}`); // e.g 1552830408824
}
</script>

读文件

<input type="file" onchange="readFile(this)">
<script>
function readFile(input) {let file = input.files[0];let reader = new FileReader();//reader.readAsText(file);//方法!
//readAsArrayBuffer,readAsText,readAsDataURL,reader.onload = function() {console.log(reader.result);};reader.onerror = function() {console.log(reader.error);};
}
</script>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/146200.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

篮球运动场景物体检测系统源码分享

篮球运动场景物体检测检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Comp…

Linux基础---13三剑客及正则表达式

一.划水阶段 首先我们先来一个三剑客与正则表达式混合使用的简单示例&#xff0c;大致了解是个啥玩意儿。下面我来演示一下如何查询登录失败的ip地址及次数。 1.首先&#xff0c;进入到 /var/log目录下 cd /var/log效果如下 2.最后&#xff0c;输入如下指令即可查看&#xf…

OpenGL渲染管线(Rendering Pipeline)介绍

渲染管线 计算机图形学中&#xff0c;计算机图形管线&#xff08;渲染管线 或简称 图形管线、流水线&#xff09;是一个概念模型&#xff0c;它描述了t图像系统将 3D场景渲染到2D屏幕所需执行的一系列步骤。渲染管线大的可以分为三个阶段。 &#xff08;一&#xff09;应用阶段…

[UTCTF2020]sstv

用goldwave和010editor打开均未发现线索&#xff0c; 网上搜索sstv&#xff0c;豆包回答如下&#xff1a; 慢扫描电视&#xff08;Slow Scan Television&#xff0c;简称 SSTV&#xff09;是一种通过无线电传输和接收静态图像的技术。 一、工作原理 SSTV 通过将图像逐行扫描并…

【GMNER】Grounded Multimodal Named Entity Recognition on Social Media

Grounded Multimodal Named Entity Recognition on Social Media 动机解决方法特征抽取多模态索引设计索引生成框架EncoderDecoder 实体定位、实体-类型-区域三元组重建 出处&#xff1a;ACL2023 论文链接&#xff1a;https://aclanthology.org/2023.acl-long.508.pdf code链接…

[Linux] Linux操作系统 进程的状态

标题&#xff1a;[Linux] Linux操作系统 进程的状态 个人主页&#xff1a;水墨不写bug &#xff08;图片来源于网络&#xff09; 目录 一、前置概念的理解 1.并行和并发 2.时间片 3.进程间具有独立性 4.等待的本质 正文开始&#xff1a; 在校的时候&#xff0c;你一定学过《…

10 张手绘图详解Java 优先级队列PriorityQueue

PriorityQueue 是 Java 中的一个基于优先级堆的优先队列实现&#xff0c;它能够在 O(log n) 的时间复杂度内实现元素的插入和删除操作&#xff0c;并且能够自动维护队列中元素的优先级顺序。 通俗来说&#xff0c;PriorityQueue 就是一个队列&#xff0c;但是它不是先进先出的…

【速成Redis】04 Redis 概念扫盲:事务、持久化、主从复制、哨兵模式

前言&#xff1a; 前三篇如下&#xff1a; 【速成Redis】01 Redis简介及windows上如何安装redis-CSDN博客 【速成Redis】02 Redis 五大基本数据类型常用命令-CSDN博客 【速成Redis】03 Redis 五大高级数据结构介绍及其常用命令 | 消息队列、地理空间、HyperLogLog、BitMap、…

带你0到1之QT编程:十五、探索QSplitter和QDockWidget的简单应用技巧

此为QT编程的第十五谈&#xff01;关注我&#xff0c;带你快速学习QT编程的学习路线&#xff01; 每一篇的技术点都是很很重要&#xff01;很重要&#xff01;很重要&#xff01;但不冗余&#xff01; 我们通常采取总-分-总和生活化的讲解方式来阐述一个知识点&#xff01; …

系统架构设计师 - 案例特训专题 - 软件工程篇

案例特训专题 - 软件工程篇 软件工程篇需求分析 ★★★★结构化需求分析 SA数据流图答题技巧 面向对象设计 ★★UML 图概况用例图类图与对象图顺序图通信图状态图活动图定时图构件图包图部署图 大家好呀&#xff01;我是小笙&#xff0c;本章我主要分享系统架构设计师 - 案例特…

【刷题—双指针】复写0、三数之和、四数之和

目录 一、复写0二、三数之和三、四数之和 一、复写0 题目&#xff1a; 注意&#xff1a;题目要求是原数组上复写 思路&#xff1a; 一、确定最后一个复写的位置。定义两个变量cur等于0&#xff0c;dest等于-1&#xff0c;让cur去遍历数组。如果cur指向的元素是0&#xff0c;…

【玉米田】

题目 代码 #include <bits/stdc.h> using namespace std; typedef long long LL;const int mod 1e8; const int M 1 << 12; LL f[13][M]; int g[13]; vector<int> state; vector<int> p[M]; int n, m; bool check(int x) {return !(x & x <&…

【Linux课程学习】make/Makefile:Linux项目自动化构建工具

&#x1f381;个人主页&#xff1a;我们的五年 &#x1f50d;系列专栏&#xff1a;Linux课程学习 &#x1f337;追光的人&#xff0c;终会万丈光芒 &#x1f389;欢迎大家点赞&#x1f44d;评论&#x1f4dd;收藏⭐文章 &#x1f349;一.make/Makefile的理解&#xff1a; …

基于SpringBoot+Vue+MySQL的国产动漫网站

系统展示 用户前台界面 管理员后台界面 系统背景 随着国内动漫产业的蓬勃发展和互联网技术的快速进步&#xff0c;动漫爱好者们对高质量、个性化的国产动漫内容需求日益增长。然而&#xff0c;市场上现有的动漫平台大多以国外动漫为主&#xff0c;对国产动漫的推广和展示存在不…

【Java集合】深入了解ArrayList实现原理

概述 1.数据存储是基于动态数组实现的&#xff0c;默认初始容量为10。 2.添加数据时&#xff0c;首先需要检查元素个数是否超过数组容量&#xff0c;如果超过了则需要对数组进行扩容&#xff08;1.5倍&#xff09;&#xff1b;插入数据时&#xff0c;需要将从插入点 k 开始到数…

BMC 虚拟i2c访问PCA9545(switch芯片)后面的设备,为什么找不到PCA9545?

1.说明 1.1 背景 无意中看到PCA9545(switch芯片)后面有设备&#xff0c;但是PCA9545设备本身是连接到物理设备i2c上的&#xff0c;然而扫描该物理i2c bus&#xff0c;却找不到该设备。此篇文章主要找一下该原因的。 1.2 参考代码 当前使用的是ast2600芯片&#xff0c;可参考…

java使用ByteBuffer进行多文件合并和拆分

1.背景 因为验证证书的需要&#xff0c;需要把证书文件和公钥给到客户&#xff0c;考虑到多个文件交互的不便性&#xff0c;所以决定将2个文件合并成一个文件交互给客户。刚开始采用字符串拼接2个文件内容&#xff0c;但是由于是加密文件&#xff0c;采用字符串形式合并后&…

threejs性能优化之gltf文件压缩threejs性能优化之glb文件压缩

在使用Three.js进行3D图形开发时&#xff0c;GLTF&#xff08;GL Transmission Format&#xff09;文件因其高效性和灵活性而广受欢迎。然而&#xff0c;随着模型复杂度的增加&#xff0c;GLTF文件的大小也会显著增加&#xff0c;这可能会对加载时间和渲染性能产生负面影响。为…

Redis数据结构之哈希表

这里的哈希表说的是value的类型是哈希表 一.相关命令 1.hset key field value 一次可以设置多个 返回值是设置成功的个数 注意&#xff0c;哈希表中的键值对&#xff0c;键是唯一的而值可以重复 所以有下面的结果&#xff1a; key中原来已经有了f1&#xff0c;所以再使用hse…

linux 操作系统下dhcrelay命令介绍和案例应用

linux 操作系统下dhcrelay命令介绍和案例应用 dhcrelay是一个用于DHCP&#xff08;动态主机配置协议&#xff09;中继的命令&#xff0c;主要功能是在没有本地DHCP服务器的子网中转发DHCP请求。这使得不同子网的DHCP客户端能够与位于其他子网中的DHCP服务器进行通信。 dhcrela…