前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在线密码生成器

在线密码生成器

作者头像
客怎眠qvq
发布2022-11-01 16:28:44
6.1K0
发布2022-11-01 16:28:44
举报
文章被收录于专栏:某菜鸟の小屋某菜鸟の小屋

📢前言

代码取自开源项目50projects50days,用作个人学习和巩固三件套的知识,增加了注释,可能会有小改动。

在线演示地址

📝实现思路及效果

注意一下几点:

  1. 各元素的位置与显示格式,尤其是对于justify-content,属性值为flex-start还是center
  2. 生成密码内容的位置不要先入为主想成input
  3. calc的用法,详情见代码注释
  4. 监听固定的几个按钮(复制、生成、5项规则),使用Math.random()生成所需字符,构建密码
  5. 复制原理的实现:将生成的字符串放置到新创建的textarea中,使用select()选中该区域的文本,使用copy命令复制成功后,将创建的textarea移除

💻代码

index.html

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 引入图标库 -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
  <link rel="stylesheet" href="style.css">
  <title>随机密码生成</title>
</head>
<body>
  <!-- 大盒子 存放 生成密码结果盒和密码格式设置盒 -->
  <div class="container">
    <!-- 结果盒 包括结果框 和 复制按钮 -->
    <div class="result-container">
      <span id="result"></span>
      <button class="btn" id="clipboard">
        <i class="far fa-clipboard"></i>
      </button>
    </div>

    <!-- 格式设置盒 -->
    <div class="settings">
      <!-- 密码长度设置 -->
      <div class="setting">
        <label>密码长度</label>
        <input type="number" id="length" min="4" max="20" value="20">
      </div>
      <!-- 密码是否有大写字母 -->
      <div class="setting">
        <label>包括大写字母</label>
        <input type="checkbox" id="uppercase" checked>
      </div>
      <!-- 小写字母 -->
      <div class="setting">
        <label>包括小写字母</label>
        <input type="checkbox" id="lowercase" checked>
      </div>
      <!-- 数字 -->
      <div class="setting">
        <label>包括数字</label>
        <input type="checkbox" id="numbers" checked>
      </div>
      <!-- 特殊符号 -->
      <div class="setting">
        <label>包括特殊符号</label>
        <input type="checkbox" id="symbols" checked>
      </div>
    </div>

    <!-- 按钮 生成结果 -->
    <button class="btn btn-large" id="generate">生成密码</button>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

代码语言:javascript
复制
@import url('https://fonts.googleapis.com/css?family=Muli&display=swap');

* {
  box-sizing: border-box;
}

body {
  background-color: #3b3b98;
  color: #fff;
  font-family: 'Muli', sans-serif;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
  padding: 10px;
}

h2 {
  margin: 10px 0 20px;
  text-align: center;
}

.container {
  background-color: #23235b;
  box-shadow: 0 2px 10px rgba(255, 255, 255, 0.2);
  padding: 20px;
  width: 350px;
  max-width: 100%;
}

.result-container {
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  /* 注意 这里不是水平垂直居中 是从行首起始位置开始排列 */
  justify-content: flex-start;
  align-items: center;
  position: relative;
  font-size: 18px;
  letter-spacing: 1px;
  padding: 12px 10px;
  height: 50px;
  width: 100%;
}

/* + 和 - 运算符的两边必须要有空白字符。比如,calc(50% -8px) 会被解析成为一个无效的表达式,解析结果是:一个百分比 后跟一个负数长度值。而加有空白字符的、有效的表达式 calc(8px + -50%) 会被解析成为:一个长度 后跟一个加号 再跟一个负百分比。 */
/* 教程链接:https://developer.mozilla.org/zh-CN/docs/Web/CSS/calc */
.result-container #result {
  word-wrap: break-word;
  max-width: calc(100% - 40px);
  overflow-y: scroll;
  height: 100%;
}

#result::-webkit-scrollbar {
  width: 1rem;
}

/* 复制按钮 */
.result-container .btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 40px;
  height: 40px;
  font-size: 20px;
}

/* 所有按钮的基本样式 */
.btn {
  border: none;
  background-color: #3b3b98;
  color: #fff;
  font-size: 16px;
  padding: 8px 12px;
  cursor: pointer;
}

.btn-large {
  display: block;
  width: 100%;
}

.setting {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

script.js

代码语言:javascript
复制
// 结果
const resultEl = document.getElementById('result')
// 密码格式设置
const lengthEl = document.getElementById('length')
const uppercaseEl = document.getElementById('uppercase')
const lowercaseEl = document.getElementById('lowercase')
const symbolsEl = document.getElementById('symbols')
const numbersEl = document.getElementById('numbers')
// 生成按钮
const generateEl = document.getElementById('generate')
// 复制按钮
const clipboardEl = document.getElementById('clipboard')

// 生成随机数
const randomFunc = {
  lower: getRandomLower,
  upper: getRandomUpper,
  number: getRandomNumber,
  symbol: getRandomSymbol
}

// 将生成的随机数 根据是否勾选该类型 构建成密码
function generatedPassword(lower, upper, number, symbol, length) {
  let generatedPassword = ''
  const typesCount = lower + upper + number + symbol
  const typesArr = [{lower}, {upper}, {number}, {symbol}].filter(item => Object.values(item)[0])

  if(typesCount === 0) {
    return ''
  }

  for(let i = 0; i < length; i += typesCount) {
    typesArr.forEach(type => {
      const funcName = Object.keys(type)[0]
      generatedPassword += randomFunc[funcName]()
    })
  }

  const finalPassword = generatedPassword.slice(0, length)

  return finalPassword
}

function getRandomLower() {
  // String.fromCharCode() 接受一个指定的Unicode值,然后返回一个字符串。
  // Math.floor() 返回小于或等于一个给定数字的最大整数 即向下取整
  return String.fromCharCode(Math.floor(Math.random() * 26 + 97))
}

function getRandomUpper() {
  return String.fromCharCode(Math.floor(Math.random() * 26) + 65)
}

function getRandomNumber() {
  return String.fromCharCode(Math.floor(Math.random() * 10) + 48)
}

function getRandomSymbol() {
  // 这里打表 按下标取符号
  const symbols = '!@#$%^&*(){}[]=<>/,.'
  return symbols[Math.floor(Math.random() * symbols.length)]
}

// 两个按钮的监听
clipboardEl.addEventListener('click', () => {
  // 创建一个文本域 赋值为已经生成的密码 调用select方法 用于选择该元素中的文本。
  const textarea = document.createElement('textarea')
  const password = resultEl.innerText

  if(!password) { return }

  textarea.value = password
  document.body.appendChild(textarea)
  textarea.select()
  // copy
  // 拷贝当前选中内容到剪贴板。启用这个功能的条件因浏览器不同而不同,而且不同时期,其启用条件也不尽相同。使用之前请检查浏览器兼容表,以确定是否可用。
  // 需要注意 document.execCommand方法已废弃  Try to avoid using it.
  document.execCommand('copy')
  // 复制成功后 删除该元素
  textarea.remove()
  alert('密码成功复制至剪贴板!')
})

generateEl.addEventListener('click', () => {
  const length = +lengthEl.value
  const hasLower = lowercaseEl.checked
  const hasUpper = uppercaseEl.checked
  const hasNumber = numbersEl.checked
  const hasSymbol = symbolsEl.checked

  resultEl.innerText = generatedPassword(hasLower, hasUpper, hasNumber, hasSymbol, length)
})
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 📢前言
  • 📝实现思路及效果
  • 💻代码
    • index.html
      • style.css
        • script.js
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档