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小時內與您取得聯系。