在这篇文章中,我将分享21个HTML技巧和代码片段,可以提高你的编码技能。
让我们开始吧。🚀
创建联系人链接
使用HTML创建可点击的电子邮件、电话和短信链接:
<!-- Email link -->
<a href="mailto:name@example.com"> Send Email </a>
<!-- Phone call link -->
<a href="tel:+1234567890"> Call Us </a>
<!-- SMS link -->
<a href="sms:+1234567890"> Send SMS </a>
创建可折叠内容
如果要在网页中折叠内容,可以使用<details>和<summary>。
<details>隐藏内容,而<summary>标记切换该内容的可见性。
使用语义元素
为您的网站选择语义元素。使您的代码有意义,并改善代码结构,可访问性和SEO。
对表单元素进行分组
使用<fieldset>对表单中的相关元素进行分组,使用<legend>标记定义标题。
增强下拉菜单
您可以使用<optgroup>标记对<select>中的相关选项进行分组。
当您使用大的菜单或一个长的选项列表时,可以使用此选项。
改善视频
poster属性可以与<video>元素一起使用,以显示图像,直到用户播放视频。
<video controls poster="image.png" width="500">
<source src="video.mp4" type="video/mp4 />
</video>
支持多种选择
您可以将multiple属性与<input>和<select>元素一起使用,允许用户一次选择/输入多个值。
显示文本下标和上标
<sub>和<sup>元素分别用于显示为下标和上标。
创建下载链接
可以将download属性与<a>元素一起使用。当用户单击链接时,下载链接的资源,而不是导航到该资源。
<a href="document.pdf" download="document.pdf"> Download PDF </a>
定义相对链接的基本URL
您可以使用<base>为网页中的所有相对URL定义基本URL。
<head>
<base href="https://shefali.dev" target="_blank" />
</head>
<body>
<a href="/blog">Blogs</a>
<a href="/get-in-touch">Contact</a>
</body>
控制图像加载
带有<img>元素的loading可用于控制浏览器加载图像的方式。它有三个值:“eager”,“lazy”和“auto”。
<img src="picture.jpg" loading="lazy">
管理翻译功能
您可以使用translate属性来指定元素的内容是否应该由浏览器进行翻译。
<p translate="no">
This text should not be translated.
</p>
设置最大输入长度
通过使用maxlength属性,可以设置用户输入的最大字符数。
<input type="text" maxlength="4">
设置最小输入长度
通过使用minlength属性,可以设置用户输入的最小字符数。
<input type="text" minlength="3">
启用内容编辑
使用contenteditable属性指定元素的内容是否可编辑。
<div contenteditable="true">
You can edit this content.
</div>
控制拼写检查
您可以将spellcheck属性与<input>元素、内容可编辑元素和<textarea>元素一起使用,以启用或禁用浏览器的拼写检查。
<input type="text" spellcheck="true"/>
确保无障碍
alt属性指定图像无法显示时的文本。包括图像的描述性alt属性,以提高可访问性和搜索引擎优化。
<img src="picture.jpg" alt="Description for the image">
定义链接的目标行为
可以使用target属性指定单击资源时链接资源的如何交互。
<!-- Opens in the same frame -->
<a href="https://shefali.dev" target="_self">Open</a>
<!-- Opens in a new window or tab -->
<a href="https://shefali.dev" target="_blank">Open</a>
<!-- Opens in the parent frame -->
<a href="https://shefali.dev" target="_parent">Open</a>
<!-- Opens in the full body of the window -->
<a href="https://shefali.dev" target="_top">Open</a>
<!-- Opens in the named frame -->
<a href="https://shefali.dev" target="framename">Open</a>
提供附加信息
title属性在用户鼠标悬停在元素上时提供有关该元素的附加信息。
<p title="World Health Organization">WHO</p>
接受特定文件类型
可以使用accept属性指定服务器接受的文件类型(仅适用于文件类型)。
<input type="file" accept="image/png, image/jpeg" />
优化视频加载
通过将preload属性与<video>元素一起使用,可以加快视频文件的加载速度,以实现更流畅的播放。
<video src="video.mp4" preload="auto">
Your browser does not support the video tag.
</video>