TML常用标签有:a标签、table标签、img标签、form标签和input标签。
作用
属性
(一)href
href是hyper reference的缩写,超链接的意思。
用于指定链接目标的ur地址,(必须属性)当为标签应用href属性时,它就具有了超链接的功能;
href=“#”表示这是一个空链接;
如果href里面地址是—个文件或者压缩包,会下载这个文件。
<a href="https://google.com">超链接到google网站的主页</a>
<a href="https://google.com">超链接到google的主页</a>
<a href="//google.com">超链接到google的主页</a>
展现形式:
点击此链接,即可到达google的主页
a标签href的取值:
1、上述代码中的网址的取值(推荐使用第三行的代码)
<a href="//google.com">超链接到google的主页</a>
由于此方式能够自动补齐相关的网络地址,前面两种写错就会报错,所以推荐使用。
2、路径
当前路径下的a里面的b,b里面的c
在当前目录下寻找index.html文件
3、伪协议
<a href="javascript:;">点击后无任何点击或刷新等动作的反应</a>
<a href="#要跳转的元素的id"></a>
点击链接的时候,会跳转到指定元素所在的位置。
<a href="mailto:abcdefg@163.com ">发邮件给我</a>
<a href="tel:12345678901">打电话给我</a>
(二)targe
用于指定链接页面的打开方式
a的target取值
1、内置名字
_blank 在空白页打开
_self 在当前页面打开
_parent 在父级窗口打开
_top 在最顶级的窗口打开
<a href="//google.com" target="_blank">超链接到google网站的主页在空白页打开</a>
2、程序员的命名
window:name(在xxx页面打开)
iframe的name(iframe现在已经很少使用了,是指内嵌窗口)
(三)download
下载页面,但目前很少用,有的浏览器不支持,尤其是手机浏览器可能不支持。
1、table标签的语法:
thead:表头
tbody:表的内容,用于定义
tfoot:表的脚部
tr:table row,表格里的行
th:表格的表头部分,其中的文本内容字体加粗居中显示
td:table data,表格数据,用于定义表格中的单元格
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th></th>
<th>小红</th>
<th>小黄</th>
<th>小蓝</th>
</tr>
</thead>
<tbody>
<tr>
<th>数学</th>
<td>90</td>
<td>60</td>
<td>80</td>
</tr>
<tr>
<th>语文</th>
<td>88</td>
<td>95</td>
<td>97</td>
</tr>
<tr>
<th>英语</th>
<td>88</td>
<td>95</td>
<td>97</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>总分</th>
<td>266</td>
<td>250</td>
<td>274</td>
</tr>
</tfoot>
</table>
</body>
</html>
第一行的th标签为空
2、table的样式
table-layout:auto;自动计算每一行的宽高
table-layout:fixed;通过列表的宽度来决定平均宽度
border-collapse:collapse; 合并边框(默认边框与边框之间不合并)
border-spacing:0;边框为0.(边框与边框之间的距离)。
作用:发出get请求,展示一张图片。
<img src="1.JPG" alt="头像" width="400" />
当前路径下的1.jpg,确定宽度为400,只写宽度高度会自适应
属性
alt:alternate的缩写,替换的意思。替换文本,图像不能显示的文字。
路径错误显示alt内容
title:提示文本。鼠标放到图像上,显示的文字。
响应
max-width:100% 所有的图片在手机上都自适应宽度,宽度最大为100%。
事件
onload/onerror 监听图片是否加载成功,加载成功时用onload,不成功是用onerror事件。确保在onerror事件能够补救。
<body>
<img id="xxx" src="dog.jpg" alt="一只小狗">
<script>
xxx.onload = function () {
console.log("图片加载成功");
};
xxx.onerror = function () {
console.log("图片加载失败");
xxx.src = "/404.jpg";
};
</script>
</body>
监听成功时,打印出成功
监听失败时,先打印出监听失败并且开始执行加载失败是的挽救图片。404.jpg文件执行
本文为作者本人的原创文章,著作权归作者本人和饥人谷所有,转载务必注明来源。
avaScript 是目前最流行的编程语言之一,正如大多数人所说:“如果你想学一门编程语言,请学JavaScript。”
FreeCodeCamp的创始人 Quincy Larson 在最近的一次采访中被问到哪种语言开发人员应该首先学习。他回答:“ JavaScript。”
“软件正在吞噬世界,JavaScript正在吞噬软件。JavaScript每年都在变得越来越占主导地位,而且没人知道最终会取代它的是什么。" 如果您没有充分的理由学习一种新语言(例如您的工作要求您维护非JavaScript代码库),那么我的建议是着重于提高JavaScript的水平。”
听我说这么多,你是不是很激动呢。这里有127端常用的JS代码片段,方便你学习和使用。
如果数组所有元素满足函数条件,则返回true。调用时,如果省略第二个参数,则默认传递布尔值。
const all = (arr, fn = Boolean) => arr.every(fn);
all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
判断数组中的元素是否都相等
const allEqual = arr => arr.every(val => val === arr[0]);
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
此代码示例检查两个数字是否近似相等,差异值可以通过传参的形式进行设置
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
此段代码将没有逗号或双引号的元素转换成带有逗号分隔符的字符串即CSV格式识别的形式。
const arrayToCSV = (arr, delimiter = ',') =>
arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
此段代码将数组元素转换成<li>标记,并将此元素添加至给定的ID元素标记内。
const arrayToHtmlList = (arr, listID) =>
(el => (
(el = document.querySelector('#' + listID)),
(el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
))();
arrayToHtmlList(['item 1', 'item 2'], 'myListID');
此段代码执行一个函数,将剩余的参数传回函数当参数,返回相应的结果,并能捕获异常。
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
此段代码返回两个或多个数的平均数。
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
一个 map()函数和 reduce()函数结合的例子,此函数先通过 map() 函数将对象转换成数组,然后在调用reduce()函数进行累加,然后根据数组长度返回平均值。
const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
此函数包含两个参数,类型都为数组,依据第二个参数的真假条件,将一个参数的数组进行分组,条件为真的放入第一个数组,其它的放入第二个数组。这里运用了Array.prototype.reduce() 和 Array.prototype.push() 相结合的形式。
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]);
// [ ['beep', 'boop', 'bar'], ['foo'] ]
此段代码将数组按照指定的函数逻辑进行分组,满足函数条件的逻辑为真,放入第一个数组中,其它不满足的放入第二个数组 。这里运用了Array.prototype.reduce() 和 Array.prototype.push() 相结合的形式,基于函数过滤逻辑,通过 Array.prototype.push() 函数将其添加到数组中。
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');
// [ ['beep', 'boop', 'bar'], ['foo'] ]
用于检测页面是否滚动到页面底部。
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
bottomVisible(); // true
此代码返回字符串的字节长度。这里用到了Blob对象,Blob(Binary Large Object)对象代表了一段二进制数据,提供了一系列操作接口。其他操作二进制数据的API(比如File对象),都是建立在Blob对象基础上的,继承了它的属性和方法。生成Blob对象有两种方法:一种是使用Blob构造函数,另一种是对现有的Blob对象使用slice方法切出一部分。
const byteSize = str => new Blob([str]).size;
byteSize(''); // 4
byteSize('Hello World'); // 11
将字符串的首字母转成大写,这里主要运用到了ES6的展开语法在数组中的运用。
const capitalize = ([first, ...rest]) =>
first.toUpperCase() + rest.join('');
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'FooBar'
将一个句子中每个单词首字母转换成大写字母,这里中要运用了正则表达式进行替换。
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalizeEveryWord('hello world!'); // 'Hello World!'
此段代码将非数值的值转换成数组对象。
const castArray = val => (Array.isArray(val) ? val : [val]);
castArray('foo'); // ['foo']
castArray([1]); // [1]
将数组中移除值为 false 的内容。
const compact = arr => arr.filter(Boolean);
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
// [ 1, 2, 3, 'a', 's', 34 ]
统计数组中某个值出现的次数
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
此代码段使用 existSync() 检查目录是否存在,然后使用 mkdirSync() 创建目录(如果不存在)。
const fs = require('fs');
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('test');
// creates the directory 'test', if it doesn't exist
返回当前访问的 URL 地址。
const currentURL = () => window.location.href;
currentURL(); // 'https://medium.com/@fatosmorina'
返回当前是今年的第几天
const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 272
将字符串的首字母转换成小写字母
const decapitalize = ([first, ...rest]) =>
first.toLowerCase() + rest.join('')
decapitalize('FooBar'); // 'fooBar'
今天的内容就和大家分享到这里,感谢你的阅读,如果你喜欢我的分享,麻烦给个关注、点赞加转发哦,你的支持,就是我分享的动力,后续会持续分享剩余的代码片段,欢迎持续关注。
本文原作者:Fatos Morina
来源网站:medium
注:并非直译
该方法用于检测给出的日期是否有效:
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
复制代码
该方法用于计算两个日期之间的间隔时间:
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-11-3"), new Date("2022-2-1")) // 90
复制代码
距离过年还有90天~
该方法用于检测给出的日期位于今年的第几天:
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 307
复制代码
2021年已经过去300多天了~
该方法可以用于将时间转化为hour:minutes:seconds的格式:
const timeFromDate = date => date.toTimeString().slice(0, 8);
timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00
timeFromDate(new Date()); // 返回当前时间 09:00:00
复制代码
该方法用于将英文字符串的首字母大写处理:
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world") // Hello world
复制代码
该方法用于将一个字符串进行翻转操作,返回翻转后的字符串:
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'
复制代码
该方法用于生成一个随机的字符串:
const randomString = () => Math.random().toString(36).slice(2);
randomString();
复制代码
该方法可以从指定长度处截断字符串:
const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString('Hi, I should be truncated because I am too loooong!', 36) // 'Hi, I should be truncated because...'
复制代码
该方法用于去除字符串中的HTML元素:
const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
复制代码
该方法用于移除数组中的重复项:
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
复制代码
该方法用于判断一个数组是否为空数组,它将返回一个布尔值:
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // true
复制代码
可以使用下面两个方法来合并两个数组:
const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];
复制代码
该方法用于判断一个数字是奇数还是偶数:
const isEven = num => num % 2 === 0;
isEven(996);
复制代码
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
复制代码
该方法用于获取两个整数之间的随机整数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);
复制代码
该方法用于将一个数字按照指定位进行四舍五入:
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
复制代码
该方法可以将一个RGB的颜色值转化为16进制值:
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(255, 255, 255); // '#ffffff'
复制代码
该方法用于获取一个随机的十六进制颜色值:
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex();
复制代码
该方法使用 navigator.clipboard.writeText 来实现将文本复制到剪贴板:
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
复制代码
该方法可以通过使用 document.cookie 来访问 cookie 并清除存储在网页中的所有 cookie:
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
复制代码
该方法通过内置的 getSelection 属性获取用户选择的文本:
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
复制代码
该方法用于检测当前的环境是否是黑暗模式,它是一个布尔值:
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)
复制代码
该方法用于在页面中返回顶部:
const goToTop = () => window.scrollTo(0, 0);
goToTop();
复制代码
该方法用于检测当前标签页是否已经激活:
const isTabInView = () => !document.hidden;
复制代码
该方法用于检测当前的设备是否是苹果的设备:
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();
复制代码
该方法用于判断页面是否已经底部:
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
复制代码
该方法用于重定向到一个新的URL:
const redirect = url => location.href = url
redirect("https://www.google.com/")
复制代码
该方法用于打开浏览器的打印框:
const showPrintDialog = () => window.print()
复制代码
该方法可以返回一个随机的布尔值,使用Math.random()可以获得0-1的随机数,与0.5进行比较,就有一半的概率获得真值或者假值。
const randomBoolean = () => Math.random() >= 0.5;
randomBoolean();
复制代码
可以使用以下形式在不适用第三个变量的情况下,交换两个变量的值:
[foo, bar] = [bar, foo];
复制代码
该方法用于获取一个变量的类型:
const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
trueTypeOf(''); // string
trueTypeOf(0); // number
trueTypeOf(); // undefined
trueTypeOf(null); // null
trueTypeOf({}); // object
trueTypeOf([]); // array
trueTypeOf(0); // number
trueTypeOf(() => {}); // function
复制代码
该方法用于摄氏度和华氏度之间的转化:
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
复制代码
该方法用于检测一个JavaScript对象是否为空:
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
*请认真填写需求信息,我们会在24小时内与您取得联系。